通过条件,我有以下与 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
是空白的,这会引发错误。
有没有一种简单的方法来创建关联,而不是完全痛苦?