views:

762

answers:

2

Heya! Rails boob here.

In my User model I could have:

has_many :tasks

and in my Task model:

belongs_to :user

Then, supposing the foreign key 'user_id' was stored in the tasks table, I could use:

@user.tasks


My question is, how do I declare the has_many relationship such that I can refer to a User's Tasks as:

@user.jobs

... or ...

@user.foobars

Thanks a heap.

+1  A: 

You could do this two different ways. One is by using "as"

has_many :tasks, :as => :jobs

or

def jobs
     self.tasks
end

Obviously the first one would be the best way to handle it.

Brent Kirby
Thanks, that sounds perfect.Unfortunately this did not work:USER MODEL:has_many :tasks, :as => :created_tasksCONTROLLER:@created_tasks = @user.created_tasks----- NoMethodError in TasksController#indexundefined method `created_tasks' for #<User:0xb6050b5c>
doctororange
:as is used for polymorphic associations not for this particular problem ...
Sam Saffron
+6  A: 

Give this a shot:

has_many :jobs, :foreign_key => 'user_id', :class_name => "Task"

Note, that :as is used for polymorphic associations.

Sam Saffron
Close:has_many :jobs, :foreign_key => 'user_id', :class_name => "Task"Thanks
doctororange
Thanks corrected it
Sam Saffron