ruby on rails - Inject attribute from association table into the associated record? -
i have following model in rails app:
class course < activerecord::base has_many :memberships has_many :members, through: :memberships, class_name: 'user' end
while course.members
returns course's members, don't access membership
model has role
attribute.
how find user role without having find membership
given course
, user
? can inject role
attribute user
somehow in context association?
user model:
class user < activerecord::base has_many :memberships, dependent: :destroy has_many :courses, through: :memberships end
here's solution, not beautiful , idiomatic though
class course < activerecord::base has_many :memberships def members user.joins(:memberships).where(id: memberships.ids).select('users.*, memberships.role') end end
a better approach, suggested through comments:
has_many :members, -> { select('users.*, memberships.role') }, class_name: 'user', through: :memberships, source: :user
Comments
Post a Comment