Rails: Multiple Associations to a Single Table

October 30, 2015 By 0 Comments

One of the first things I’ve learnt when dealing with data models in Ruby on Rails is the standard convention for mapping a a relationship. (second to  rails generate model Article) The general rule is to take the singular form of the table name, and add _id . Pretty simple. We’d end up with something like this:

Ok, looks good. Now, what about a slightly different case; where we need two distinct mappings to the users table? Lets say our articles need to be approved before they can be seen, and we want to store the user who approved them? Following the convention to the letter would give us two user_id  fields. So what can we do about this?

After a bit of digging, it turns out that the way round this is to map a class onto the associations. So it would look like this:

And in the model file, article.rb:

This creates the association as expected, treating author  and approver  as User, just as if you’d used user_id.