Hi,
I know I am missing something very big regarding the changes with respect to activerecord in Rails 3.
I can't find the explanation. And I'm sure someone will kick my ass for not finding the right piece of info in the docs and guides. Please do.
I have a working piece of code but I don't like it.
So. Very basic association:
class Project < ActiveRecord::Base has_many :tasks end
class Task < ActiveRecord::Base belongs_to :project end
The task table has the foreign key: t.integer "project_id"
I can create a task this way, and the resulting task has the correct project id stored
@project = Project.find(1) @task = @project.tasks.build(params[:task]) @task.save
Now I get the project record using the Rails 2 way:
@project = Project.find(1) triggers: Project Load (0.2ms) SELECT `projects`.* FROM `projects` WHERE (`projects`.`id` = 1) LIMIT 1
@project.inspect outputs: #<Project id: 1, name: "test", created_at: "2010-11-18 15:15:23", updated_at: "2010-11-18 15:15:23">
@project.tasks.inspect shows: [#<Task id: 1, title: "test", project_id: 1, created_at: "2010-11-18 15:20:06", updated_at: "2010-11-18 15:20:06">]
But now I want to use the Rails 3 way:
@proj = Project.where(:id => params[:id]) trigger: Project Load (0.3ms) SELECT `projects`.* FROM `projects` WHERE (`projects`.`id` = 1)
@proj.inspect shows: [#<Project id: 1, name: "test", created_at: "2010-11-18 15:15:23", updated_at: "2010-11-18 15:15:23">]
And @proj.tasks.inspect gives: NoMethodError (undefined method `tasks' for #<ActiveRecord::Relation:0x00000103922f30>):
Now, if I use: @proj[0].tasks.inspect then I get the tasks for the project.
Is this the right way? I have the feeling it is not.
Cheers.