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

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -