DEV Community

Asad Akbar
Asad Akbar

Posted on

Setting a foreign key on Active Record Associations

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
end

class Floor
  has_one  :copy_machine, foreign_key: :floor_id
end

class CopyMachine
  belongs_to :floor
end
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 https://www.viget.com/articles/exploring-the-inverse-of-option-on-rails-model-associations/.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay