gerky
gerky

Reputation: 6417

Rails - Associating a model with a user

I've just started a Rails application set up with Devise. Now, I'm planning to add a new model, Product, that will have a one-to-many relationship with User. I've generated the Product model using the scaffold generator. Then, I've added the belongs_to :user to product, and has_many :products to user. Should I run a migration after adding the associations? I'm using mysql for my database.

Now, I'm unsure of how to associate it with the current user. I'm trying to set the user of the product in the products controller create action. Something like @product.user = current_user. But it doesn't actually work. I've read that I should set the user.id of a product to achieve this, but I'm not really sure how to do that. Step-by-step tutorial links and detailed explanations would really help. Thanks a lot!

Upvotes: 1

Views: 96

Answers (1)

Kashiftufail
Kashiftufail

Reputation: 10885

First run migration of product then make another migration or just add

   t.integer :user_id 

in product migration run migration then you can

     @product.user = current_user

Upvotes: 2

Related Questions