Rails has_many:通过:条件。如何创建关联?

时间:2012-09-26 12:31:40

标签: ruby-on-rails ruby has-many-through has-many

我有以下与has_many相关的模型以及条件。

(请注意Membership验证是否存在kind属性)

class User < ActiveRecord::Base
  has_many :memberships
  has_many :founded_groups,
    :through => :memberships,
    :source  => :group,
    :class_name => 'Group'
    :conditions => {'memberships.kind' => 'founder'}
  has_many :joined_groups, ... # same as above, but the kind is 'member'
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :founders, ...        # these two mirror the User's
  has_many :regular_members, ... #
end

class Membership < ActiveRecord::Base
  validates_presence_of :user_id
  validates_presence_of :club_id
  validates_presence_of :kind   # <-- attention here!

  belongs_to :user
  belongs_to :group
end

Rails似乎喜欢上面的代码(至少它没有吠叫它)。但后来发生了这种情况:

> user = User.create(...) # valid user
> club = Club.create(...) # valid club
> user.founded_clubs = [club]

ActiveRecord::RecordInvalid: Validation failed: kind can't be blank

> club.founders << user

ActiveRecord::RecordInvalid: Validation failed: kind can't be blank

我假设rails会占用我的代码的{'memberships.kind' => 'founder'}部分并在创建关联时使用它,但似乎并非如此。所以新成员资格kind是空白的,这会引发错误。

是否有一种简单的方法可以创建关联,而不是完全痛苦?

1 个答案:

答案 0 :(得分:2)

这肯定会有效:

> user = User.create(...) # valid user
> club = Club.create(...) # valid club
> user.memberships.create(:club_id => club.id, :kind => 'founder')

我不确定,但这可行:

> user.memberships.create(:club => club, :kind => 'founder')