2010-10-28 59 views
1

我有以下型号:通过两条轨道HABTM协会联合表

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, :class_name => "User", :foreign_key => :friend_id 
    has_and_belongs_to_many :friend_groups 
end 

class FriendGroup < ActiveRecord::Base 
    has_and_belongs_to_many :friendships 
end 

我怎样才能宣布FriendGroup has_and_belongs_to_many :friends through :friendships

我想FriendGroup.friend_ids,所以在形式上我可以设置一个字段'friend_group[friend_ids][]',只需拨打FriendGroup.create(params[:friend_group])没有任何额外的逻辑。

回答

0

我很困惑你想用FriendGroups做什么。

你的基本友好建模为:

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, :class_name => "User" 
end 

class User < ActiveRecord::Base 
    has_many :friendships 
    has_many :friends, :through => :friendships 
end 

您是否希望您在传递的所有用户之间的质量创造友谊的记录?这可能是某种排列问题。不是你需要另一个模型的东西。也许是友谊的类方法,如interconnect(user_ids)

如果你想找到彼此都是朋友的用户组,听起来像你正在进入图论和连接。

编辑:

在FriendGroups只是被朋友泛型容器附有我会做这样的事情的名称的情况下:

class User < ActiveRecord::Base 
    has_many :friend_groupings 
    has_many :friend_groups 
    has_many :friendships 
    has_many :friends, :through => :friendships 
end 

class FriendGrouping < ActiveRecord::Base 
    belongs_to :friend_group 
    belongs_to :friend 
end 

class FriendGroup < ActiveRecord::Base 
    has_many :friend_groupings 
    has_many :friends, :class_name => "User", :through => :friend_groupings 
    belongs_to :user 

    validates_presence_of :name # Name of FriendGroup 
end 

我可能会根据用户巢FriendGroups,和FriendGroups为FriendGroupings提供了accept_nested_attributes_。我会在FriendGroup控制器中执行此操作,并且在FriendGroup的视图中允许用户设置组的名称,然后为每个朋友提供复选框以放入组中。对于他们选择的每个朋友,在FriendGroup和用户之间创建一个新的FriendGrouping。这应该让你得到你想要的。

+0

这是它在网站上的工作原理。当用户添加好友时,会创建“友谊”对象。然后他可以进入他的朋友列表,选择其中的一部分,并创建一个名为“FriendGroup”(例如家庭,同学等)。 问题是用户应该提交什么来创建一个组:'user_ids'或'friendship_ids'。通过'friendship_ids',模型中的一切都很简单,但是在我看来,更符合逻辑和一致性的是,您实际上创建了一组用户,而不是一组关系。所以我想保留'friendship_ids'对用户不可见。 – RocketR 2010-10-28 21:19:07

+0

我编辑了处理FriendGroups的答案。我认为这更多的是你正在寻找的东西。 – 2010-10-28 23:15:42

+0

不错,谢谢。 – RocketR 2010-10-30 09:52:35

0

类FriendGroup <的ActiveRecord :: Base的 has_and_belongs_to_many:朋友:通过=>:friendgroups 结束

0

嘛,我发现,但一个线,但两线解决方案,它看起来很优雅:

class FriendGroup < ActiveRecord::Base 
... 
    attr_accessor :friend_ids 
    before_create {|fg| fg.friendships = Friendship.find_all_by_user_id_and_friend_id(fg.user_id, fg.friend_ids)}