0

I have a User and a Role model and I am trying to make a many-to-many relationship.

Why do I need both of these lines?

has_many :user_roles
has_many :users, through: :user_roles

Doesn't the second line imply the first? When does the second line not imply the first? Why doesn't Rails just do its magic thing and make the second imply the first?

Jwan622
  • 11,015
  • 21
  • 88
  • 181
  • 1
    You can use "has_and_belongs_to_many" association instead. It really depends on what you are planning to do with the associations. Take a look at this SO: http://stackoverflow.com/questions/2780798/has-and-belongs-to-many-vs-has-many-through, and this Guide: http://guides.rubyonrails.org/association_basics.html – dimitry_n Feb 17 '15 at 17:17
  • The second line doesn't imply the first in situations where the `has_many :user_roles` association has any options, ie is anything other than totally standard in it's setup. So, you could leave it implied, but then if you wanted to make any changes to the `has_many :user_roles` association you'd need to add it in, and specify the options. At this point, you've potentially got a battle between the relationship which is specified and the one that is implied. Confusion results. Better to make it explicit, and obvious what's happening. It's not like it costs you anything to write those chars. – Max Williams Feb 17 '15 at 17:19
  • still confused... can you edit that post Max Williams? – Jwan622 Feb 18 '15 at 06:16

1 Answers1

0
class Role < ActiveRecord::Base
  has_many :user_roles
  has_many :users, through: :user_roles

allows you to bypass the intermediate steps. @role.users is valid code if you include the through :user_roles. Otherwise you would need to use @role.user_roles.users to get the same list.

Aaron Washburn
  • 300
  • 2
  • 10