Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reflect in the database a new belongs_to and has_many relationship in Ruby on Rails

Tags:

I am new to rails (usually a python guy) and have just been trying to build a simple task manager application for fun. I am using Devise for authentication and have a single Task object I am trying to relate to a user. I have added the following to the Task model:

class Task < ActiveRecord::Base     belongs_to :user end 

and I have added the following in my User model for Devise:

class User < ActiveRecord::Base    has_many :tasks     <<normal Devise stuff>> end 

Whenever I added this information I then ran: rake db:migrate. It then gave me an error that the database field did not exist for user_id when I tried to do anything with it.

I am sure it is something rather simple that I am missing. Thanks for the help.

like image 366
Ken I. Avatar asked Jan 06 '11 20:01

Ken I.


2 Answers

Adding a belongs_to (or any other) relationship to your model only tells active record that models are linked logically. This gives you access to methods like task.user. For this to actually work, the instances must be linked via database fields.

This is the step you're missing: you need to create a migration that will add a column to the Task table indicating which user it belongs to.

rails g migration AddUserIdToTasks user_id:integer 

Note AddUserIdToTasks can be whatever name you want. It makes no difference. You can then open db/migrations/add_user_to_tasks and see what it does. Usually self.up will modify the database how you want it and self.down will do the opposite (so, in this case, remove the used_id).

Then to actually execute the SQL commands to alter the database table and schema, run

rake db:migrate 
like image 90
David Sulc Avatar answered Oct 18 '22 09:10

David Sulc


You need to generate a migration to add the foreign key first:

rails g migration AddUserIdToTasks user_id:integer 

Then run db:migrate

And if you want the user to be able to reference the association as user.dreams, you need to add :class_name => 'Task' to the has_many line in the User model.

like image 37
idlefingers Avatar answered Oct 18 '22 11:10

idlefingers