DEV Community


Setting a foreign key on Active Record Associations

Asad Akbar
・1 min read

Just a random thing I learned and wanted to document. I was struggling to save a double nested association coming in from a form, and I kept hitting an error that the record at the bottom of the nesting couldnt be created because its parent hadnt been created.

class Building
  has_many :floors

class Floor
  has_one  :copy_machine, foreign_key: :floor_id

class CopyMachine
  belongs_to :floor
Enter fullscreen mode Exit fullscreen mode

Well after some digging I figured out that since I had defined the foreign key, rails is unable to guess the inverse from the class name, so the parent can't be saved. I don't know why I set that foreign key, since I didn't actually need it since the column was named according to the class.

I was able to remove it and the error was gone. But if I had needed it to be set, say the foreign key on CopyMachine was "level_id", then the inverse_of key would need to be passed when defining the has_one relationship. This is apparently the case when defining the foreign_key or the class_name parameters.

The paragraph at the bottom of this article helped me figure this out

Discussion (0)