Techblog

Tech Blog

Our latest geek adventures!

11 July Multiple relations between 2 tables in Rails

Posted by Gert-Jan on in Databases, Ruby on Rails

Just a small post about something I figured out recently…

If 2 database tables have a relation, in Rails you model it using the belongs_to and the has_one (has_many) attributes. Rails guesses the foreign key based on the names of the tables and its field names. In my setup I had 4 relations between 2 tables, so Rails couldn’t guess the foreign key’s by itself. All I had to do to make it work, was to specify the foreign keys and the related class:

  belongs_to :var_1, :foreign_key => "id_1", :class_name => "RelatedClass"
  belongs_to :var_2, :foreign_key => "id_2", :class_name => "RelatedClass"
  belongs_to :var_3, :foreign_key => "id_3", :class_name => "RelatedClass"
  belongs_to :var_4, :foreign_key => "id_4", :class_name => "RelatedClass

One Response to “Multiple relations between 2 tables in Rails”

  1. Glenn Says:

    Hey Guys, talked to Jeroen earlier. I have to say that I gave up on my rails project. And turned to the dark side of asp.
    For really fast RAD I used ironspeed designer. So much easier than rails :)

Leave a Reply