使用 Rails 创建与其他 2 个模型相关的模型
我有这样的模型:
class Person
has_many :groups
has_many :group_memberships, :foreign_key => "member_id"
end
class Group_Membership
belongs_to :member, :class_name => 'Person'
belongs_to :group
end
class Group
belongs_to :person
has_many :group_memberships
has_many :members, :class_name => "Person", :through => "group_memberships", :foreign_key => "member_id"
end
我只是在徘徊,如果一个人想要加入一个组,这个人将创建一个 group_membership ,它需要该人本身的 id 和该组的 id。如果我在组视图上执行一个没有表单的创建按钮是对的吗?既然我必须通过 build
传递两个 id,那么 def create
会怎样呢?谢谢。
I have models like that:
class Person
has_many :groups
has_many :group_memberships, :foreign_key => "member_id"
end
class Group_Membership
belongs_to :member, :class_name => 'Person'
belongs_to :group
end
class Group
belongs_to :person
has_many :group_memberships
has_many :members, :class_name => "Person", :through => "group_memberships", :foreign_key => "member_id"
end
I was just wandering, if a Person wants to join a group, the person will create a group_membership that will need both the id of the Person itself and the Group. If I do a single create button without a form on the group view would be right? And how would be the def create
since I will have to pass both ids via build
right? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您更有可能从 Person 或 Group 实例创建 GroupMembership,因此只需要一个 id。因此,当您谈论使用组视图时 - 我假设您的意思是在您的 show 视图中包含某种“添加成员”表单,因此您对该表单的操作可能称为
create_membership
看起来像这样:More likely you will create a GroupMembership from a Person or Group instance, so only need one id. So when you're talking about using the group view - I assume you mean to include some sort of "add member" form in your show view, so your action for that form might be called
create_membership
and look something like this: