Dominic Goulet
Dominic Goulet

Reputation: 8113

Rails naming conventions when having two relations to the same model

My question is more related to naming conventions than programmation I guess.

Let's assume an application where users can create new articles (so they are the owner of these articles) and where you can add article "editors", who can only update the article content.

class User
  include Mongoid::Document
  has_many :articles # as owner of the articles
  has_and_belongs_to_many :articles # as editor of the articles
end

class Article
  include Mongoid::Document
  belongs_to :user
  has_and_belongs_to_many :editors, :class_name => 'User'
end

What I want to know is how I should call the articles association in my User model. I mean, an article has an author and editors, which seems strong naming conventions to me, but a user has articles he created and articles he is the editor. How would you call/name/declare the last 2 associations?

Upvotes: 1

Views: 172

Answers (1)

Matzi
Matzi

Reputation: 13925

I would call them as :edited_articles, and :authored_articles or :owned_articles, or something similarly straightforward names. Just dont forget to add the :class_name and :foreign_key or :through qualifiers to them.

Update:

For has_and_belongs_to_many relation you need a connection table, which is by default, is named of the two joined table. E.g. articles_users in your case. In this table you will propably have two ids, user_id and article_id. This way rails connects your models automatically.

has_and_belongs_to_many :editors, :class_name => 'User', :foreign_id => 'user_id'

Of course if you call it editor_id in the join table then use that. And the opposite, on the user side should work too.

Upvotes: 3

Related Questions