Polymorphic Associations in Rails
-
22-08-2019 - |
Question
How do polymorphic associations work in Rails? What are their advantages? Is there a way to add belongs_to
method just by running a migration?
Solution
Ryan has a railscast about this that is pretty good.
Belongs_to isn't something you add to a migration, you add it to the model. In the migration, you have to add the foreign key column. For example if you have a post model that belongs to a user, you'd add the user_id column to the post activerecord in a migration. Then you add
belongs_to :user
in the post model separately. Then rails will do its magic in the background to give you the proxy collections in the user model.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow