0
我有以下與has_many通過條件相關的模型。Rails has_many:通過with:條件。我如何創建關聯?
(注意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
滑軌似乎喜歡上面的代碼(至少其不向吠叫它)。但隨後發生這種情況:
> 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
我假設軌道將採取我的代碼{'memberships.kind' => 'founder'}
部分和創建關聯的時候使用它,但它似乎並不如此。所以新會員的kind
是空白的,並且會引發錯誤。
有沒有一種簡單的方法來創建協會,而不是一個完整的痛苦?
感謝。我希望找到某種語法,允許我創建給定多個元素的會員資格 - 一個俱樂部和兩個用戶,或一個用戶和兩個俱樂部。看來,我只需要遍歷「很多」部分並手動創建關聯。好吧。 – kikito