I have 2 models
class User < ActiveRecord::Base has_many :products end class Product < ActiveRecord::Base belongs_to :user end
Do I need to add a column user_id to the Product table or does rails add it by default ?
They essentially do the same thing, the only difference is what side of the relationship you are on. If a User has a Profile , then in the User class you'd have has_one :profile and in the Profile class you'd have belongs_to :user . To determine who "has" the other object, look at where the foreign key is.
Polymorphic relationship in Rails refers to a type of Active Record association. This concept is used to attach a model to another model that can be of a different type by only having to define one association.
You do need to manually add the user_id
column to the Product
model. If you haven't created your model yet, add the reference in the column list to the model generator. For example:
rails generate model Product name:string price:decimal user:references
Or, if your Product
model already exists what you have to do is:
rails g migration addUserIdToProducts user_id:integer
That will generate a migration that properly add the user_id
column to the products
table. With the column properly named (user_id), Rails will know that's your foreign key.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With