Collection.build or collection.create gives "ArgumentError: wrong number of arguments (1 for 0)"

I have a Project that has_many Tasks. Tasks belongs to a Project. When
I try the following:

project = Project.new
project.tasks.build

I get:

s = Project.new
=> #<Project:0x25f9e28 @attributes={“name”=>"", “end_at”=>nil,
“updated_at”=>nil, “published_at”=>nil, “user_id”=>nil,
“created_at”=>nil}, @new_record=true>

s.tasks.build
ArgumentError: wrong number of arguments (1 for 0)
from /Applications/Locomotive2/Bundles/
standardRailsMar2007.locobundle/i386/lib/ruby/gems/1.8/gems/
activerecord-1.15.3/lib/active_record/associations/
has_many_association.rb:13:in initialize' from /Applications/Locomotive2/Bundles/ standardRailsMar2007.locobundle/i386/lib/ruby/gems/1.8/gems/ activerecord-1.15.3/lib/active_record/associations/ has_many_association.rb:13:innew’
from /Applications/Locomotive2/Bundles/
standardRailsMar2007.locobundle/i386/lib/ruby/gems/1.8/gems/
activerecord-1.15.3/lib/active_record/associations/
has_many_association.rb:13:in `build’
from (irb):2

Am I doing something stupid? I would expect this to work.

Thanks,

Scott

On Nov 28, 2007 11:48 PM, Scott [email protected] wrote:

I have a Project that has_many Tasks. Tasks belongs to a Project. When
I try the following:

project = Project.new

You need to do project.save before adding any tasks. Otherwise how
will ActiveRecord know what project_id to record for a given task?


Greg D.
http://destiney.com/

class Project < ActiveRecord::Base
belongs_to :user
has_many :tasks
end

class Task < ActiveRecord::Base
belongs_to :project
belongs_to :task_type
end

On Nov 29, 2007 12:48 AM, Scott [email protected] wrote:

=> #<Project:0x25f9e28 @attributes={“name”=>“”, “end_at”=>nil,
“updated_at”=>nil, “published_at”=>nil, “user_id”=>nil,
“created_at”=>nil}, @new_record=true>

s.tasks.build
ArgumentError: wrong number of arguments (1 for 0)
from /Applications/Locomotive2/Bundles/
standardRailsMar2007.locobundle/i386/lib/ruby/gems/1.8/gems/
activerecord-1.15.3/lib/active_record/associations/
has_many_association.rb:13:in `initialize’

Post your models. Possibly has_many declaration is wrong, or Task is
not derived from ActiveRecord::Base? Does

Task.new

give expected results from the console?

From the rdoc on has_many:

collection.build(attributes = {}) - returns a new object of the
collection type that has been instantiated with attributes and linked
to this object through a foreign key but has not yet been saved.
Note: This only works if an associated object already exists, not if
it’s nil!

You shouldn’t have to save it… that’s the whole point.