ruby on rails - How to model an owner and members with a has_many :through association? -
in rails application have event , user models. business rules dictate event has 1 owner , many members, , owner must member. inverse user having many 'owned events' , 'events' (events he/she member of not owner). had planned model association so:
class event < activerecord::base has_many :event_members, dependent: :destroy has_one :owner, through: :event_members, source: :user, conditions: { owner: true } has_many :members, through: :event_members, source: :user end class eventmember < activerecord::base belongs_to :event belongs_to :user end class user < activerecord::base has_many :owned_events, through: :event_members, conditions: { owner: true } has_many :events, through: :event_members end
i thought ensure 1 owner , owner included in members association free. however, doesn't work since can't specify has_one through collection - :event_members association.
is there better way model this? add transient 'owner' attr on event queries eventmember owner flag - work setting owner (i.e. can grab eventmember record created , make sure owner flag set)?
what adding owner
attribute on join model eventmember
(also field of type boolean in event_members
table, default value of false
). access owner
, owned_events
methods on each respective model.
class event < activerecord::base has_many :event_members has_many :members, :through => :event_members, :source => :user def owner event_members.ownerships.map(&:user).first end end class eventmember < activerecord::base belongs_to :event belogns_to :user scope :ownerships, -> { where(:owner => true) } end class user < activerecord::base has_many :event_members has_many :events, :through => :event_members def owned_events event_members.ownerships.map(&:event) end end
the event
object may have responsibility of making user owner.
class event def make_owner!(user) membership = event_members.where(:user_id = user).first membership.owner = true membership.save end end
maybe place logic in there enforce 1 owner , abstract part of make_owner!
eventmember
depending on how messy gets in application.
Comments
Post a Comment