使用 Rails 创建与其他 2 个模型相关的模型

发布于 2024-11-08 07:19:30 字数 580 浏览 0 评论 0原文

我有这样的模型:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

可可 2024-11-15 07:19:49

您更有可能从 Person 或 Group 实例创建 GroupMembership,因此只需要一个 id。因此,当您谈论使用组视图时 - 我假设您的意思是在您的 show 视图中包含某种“添加成员”表单,因此您对该表单的操作可能称为 create_membership 看起来像这样:

def create_membership
  @group = Group.find params[:id]
  if @group.group_memberships.create( :member_id => params[:member_id])
    redirect_to @group
  else
     render :action => 'show'
  end
end

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:

def create_membership
  @group = Group.find params[:id]
  if @group.group_memberships.create( :member_id => params[:member_id])
    redirect_to @group
  else
     render :action => 'show'
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文