1

I have two classes (organisation.rb and user.rb) which are linked through a join table via ActiveRecord with a many to many relationship. A user can belong to many organisations, and an organisation can have many users.

Initially, I represented this relationship in this manner and this worked fine:

class Organisation < ActiveRecord::Base
  has_many :members, through: :memberships, source: :user
  has_many :memberships
end

class User < ActiveRecord::Base
  has_many :organisation_members, through: :memberships, source: :organisation
  has_many :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :organisation
end

I asked a friend to review my pull request and he suggested that the Rails convention is to name the join table with a lexical ordered list of the tables to be joined. I searched and confirmed this:

Rails naming convention for join table

As such, I reverted my migrations and started anew, with the new relationships:

class Organisation < ActiveRecord::Base
  has_many :members, through: :organisations_users, source: :user
  has_many :organisations_users
end

class User < ActiveRecord::Base
  has_many :organisation_memberships, through: :organisations_users, source: :organisation
  has_many :organisations_user
end

class OrganisationsUser < ActiveRecord::Base
  belongs_to :user
  belongs_to :organisation
end

Having made these changes, a number of my tests failed due to not recognising the model 'organisation_user.rb'. I then tried 'organisations_users.rb', and also no luck. This was due to my ignorance of rails' pluralisation, and therefore naming the join table model correctly resulted in all tests passing. As described above, the correct naming is:

class OrganisationsUser

This results in a rather strange model name of a pluralised organisation followed by a singular user.

I understand that this is technically correct. The model name should singular, however it isn't particularly easy to understand when compared with the 'memberships' join table.

What is the correct way to handle this - should I revert back to memberships, find a way to override Rails' default pluralisation, or continue with the awkwardly named status quo?

Community
  • 1
  • 1
  • 3
    That *lexical ordering* is for `has_and_belongs_to_many` only. You don't need to worry about as you are using `has_many, :through` – Pavan Jul 13 '16 at 17:11
  • @Pavan's comment has it right. Your first implementation is more correct. – flanger001 Jul 13 '16 at 18:03
  • I think your second code doesn't work because you need to change this: `has_many :organisations_user` to `has_many :organisations_users`. That said either is acceptable and you should do what makes the most sense to you and your team. – ruby_newbie Jul 13 '16 at 18:49

0 Answers0