如何关联模特?

时间:2016-03-04 21:58:06

标签: ruby-on-rails ruby

我正在构建一个包含用户和组的ROR应用程序,我希望能够将它们与名为Memberships的关联模型链接起来。

我的问题是,当我尝试创建一个包含一个成员的组时,新组的members数组始终为空。

我尝试创建一个这样的组:

def create (user)
  @group = Group.new(create_group_params)
  user.join(@group)
  user.save
  @group.save
end

但是当我打印出来时@group.members为空。如何让用户成为该组的成员?

以下是我的模特:

Group.rb

class Group < ActiveRecord::Base
  has_many :passive_memberships, class_name: "Membership",
                                foreign_key: "club_id",
                                  dependent: :destroy

  has_many :members, through: :passive_memberships, source: :member
end

User.rb

 class User < ActiveRecord::Base
  has_many :active_memberships, class_name:  "Membership",
                                foreign_key: "member_id",
                                dependent:   :destroy

  has_many :memberships, through: :active_memberships, source: :club

  def join(group)
    active_memberships.create(club_id: group.id)
  end
end

Membership.rb

class Membership < ActiveRecord::Base
  belongs_to :member, class_name: "User"
  belongs_to :club, class_name: "Group"
  validates :member_id, presence: true
  validates :club_id, presence: true
end

1 个答案:

答案 0 :(得分:0)

喔。我必须在用户加入之前保存该组。

def create (user)
  @group = Group.new(create_group_params)
  @group.save
  user.join(@group)
  user.save
end