I have the following models associated with has_many through with conditions.
(Note that Membership validates the presence of the kind attribute)
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 seems to like the code above (at least it doesn’t bark to it). But then this happens:
> 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
I was assuming that rails would take the {'memberships.kind' => 'founder'} part of my code and use it when creating the association, but it doesn’t seem to be the case. So the new membership’s kind is blank, and that throws an error.
Is there an easy way to create the associations, without it being a complete pain?
This will work for sure:
I’m not sure, but this may work: