Rails 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])
没有任何额外的逻辑。
I have the following models:
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
How can I declare that FriendGroup has_and_belongs_to_many :friends through :friendships
?
I would like to have FriendGroup.friend_ids
, so in the form I can just set a field 'friend_group[friend_ids][]'
and just call FriendGroup.create(params[:friend_group])
without any additional logic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我对你想用 FriendGroups 做什么感到困惑。
您的基本友谊被建模为:
您是否希望在您传入的所有用户之间批量创建友谊记录?这可能是某种排列问题。不需要另一个模型。也许是 Friendship 上的类方法,例如
interconnect(user_ids)
。如果您想找到彼此都是朋友的用户组,那么听起来您正在研究图论和连通性。
编辑:
如果 FriendGroups 只是带有附加名称的朋友的通用容器,我会这样做:
我可能会将 FriendGroups 嵌套在 Users 下,并让 FriendGroupsaccept_nested_attributes_for FriendGroupings。我将在 FriendGroup 控制器中执行此操作,并在 FriendGroup 视图中允许用户设置组的名称,然后为他们的每个朋友提供复选框以放入组中。对于他们选择的每个朋友,在 FriendGroup 和用户之间创建一个新的 FriendGrouping。这应该能让你得到你想要的。
I'm confused on what you are trying to do with FriendGroups.
Your basic Friendship is modeled as:
Are you looking to mass create Friendship records between all the Users that you pass in? That's probably some sort of permutations problem. Not something you would need another model for. Maybe a class method on Friendship like
interconnect(user_ids)
.If you're wanting to find groups of Users that are all friends of each other that sounds like you're getting into Graph Theory and connectivity.
EDIT:
In the case of FriendGroups just being generic containers of friends with a name attached I would do something like this:
I would probably nest FriendGroups under Users, and have FriendGroups accept_nested_attributes_for FriendGroupings. I would do this in the FriendGroup controller and in the view for the FriendGroup allow the user to set the name of the group and then give them checkboxes for each of their friends to put in the group. For each friend they select create a new FriendGrouping between the FriendGroup and the User. That should get you what you want.
类 FriendGroup < ActiveRecord::基础
has_and_belongs_to_many :朋友,:通过 => :朋友组
结尾
class FriendGroup < ActiveRecord::Base
has_and_belongs_to_many :friends, :through => :friendgroups
end
好吧,我发现不是单行解决方案,而是两行解决方案,看起来足够优雅:
Well, I found not the one-line, but two-line solution which looks elegant enough: