简体   繁体   中英

Rails field on join entity in has_many through relationship

I may be going about this the wrong way but after reading various SO articles and the Rails docs on associations and scopes, I'm not much wiser.

I have a many-to-may relationship expressed like so:

class User < ActiveRecord::Base
  has_many :user_program_records
  has_many :programs, through: :user_program_records
end

class Program < ActiveRecord::Base
  has_many :user_program_records
  has_many :users, through: :user_program_records
end

class UserProgramRecord < ActiveRecord::Base
  belongs_to :user
  belongs_to :program

  # has a field "role"
end

The idea is that there are many users in the system and many programs. Programs have many users in them and users may belong to multiple programs. However - within a given program, a user can only have one role.

What I'd really like to be able to write is:

Program.first.users.first.role

and have that return me the role (which is just a String ).

What's the cleanest way to do this? Basically, once I've scoped a user to a given program, how do I cleanly access fields on the relevant join table?

You are thinking about it slightly wrong:

user.role

Would be very ambiguous as a user can have different roles in different programs. Instead you need to think of the join entity as a thing of its own.

The easiest way is to select the join model directly:

program = Program.includes(:user_program_records, :users).first
role = program.user_program_records
                .find_by(user: program.users.first)
                .role

You can use stuff like association extensions and helper methods to make this a bit sexier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM