I am currently trying to create a fairly simple association in Rails, but it is proving more difficult than I thought.
I have 3 models, User, Dealer and Role. User/dealer is many to many. Users can have many roles, but they should be specific to a dealership – i.e. a user can have the roles manager and director at one dealership, manager only at another, and be chairman in another.
The outcome I am looking for is that I will be able to do user.dealer.roles and (e.g. for the first dealer) it would return manager and director. The same would happen if I did dealer.user.roles.
My classes look as follows:
class User :dealer_users has_many :dealer_user_roles, :through => :dealer_users has_many :roles, :through => :dealer_user_roles end class Dealer :dealer_users has_many :dealer_user_roles, :through => :dealer_users has_many :roles, :through => :dealer_user_roles end class Role :dealer_user_roles has_many :users, :through => :dealer_users end
The tables look like (green tables):

I am trying to seed the database using the following code:
dealer = Dealer.where(name: Faker::Company.name).first_or_create user = User.where(email: Faker::Internet.email).first_or_create user.first_name = Faker::Name.first_name user.last_name = Faker::Name.last_name user.password = 'password' user.password_confirmation = 'password' dealer.users user.id).first.roles 1 + Random.rand(4))
This results in an error, which is: "Cannot modify association 'User#roles' because it goes through more than one other association."
Can anyone assist by telling me where I am going wrong, and how I can put it right?
Off the top of my head, I would model it as:
This makes it easier to deal with, and also puts the roles where they actually belong – on the combination of user/dealer which I’ve called employment.
you can then say
EDIT: with scopes all of these should do what you want.