Has_many relationships

In my model I have two classes, a donation class and a good class. A
donation can have mulitple goods, so I set up a has_many relationship
between the two objects.

class Donation < ActiveRecord::Base
has_many :goods

class Good < ActiveRecord::Base
belongs_to :donation

In my view (donation/new.html.erb), I add goods to a donation the
following way;






This will create the following @params after submitting the form.

{“commit”=>“Submit”,
“authenticity_token”=>“727eec63cfc5b40ee935c0d3478476661893b52c”,
“donation”=>{“goods”=>
{“1”=>
{“item”=>“books”,
“description”=>“Children books”},
“2”=>
{“item”=>“shoes”,
“description”=>“Leather Boots”},
“3”=>
{“item”=>“blankets”,
“description”=>“wool blankets”},}}}

The donation controller:

class DonationsController < ApplicationController
def create
@donation = Donation.new(params[:donation])

So, I was hoping that ruby on rails automatically generates the goods
and adds them to the donation object, but when create is called, i get
the following error on the first line;

ActiveRecord::AssociationTypeMismatch in DonationsController#create

Good expected, got Array

Any help is appreciated.

Thanks. Is there some way to manipulate the @params info so that ruby
automates this process?

On Jan 29, 1:21 pm, Chris O. [email protected]

There is a lot of magic in rails, but not that much.

Based on the @params info that you showed you will have to extract the
donation info, create the object and manually make the relations to the
goods.

ex
def create
@donation = Donation.new(params[:donation])
params[:donation][:goods].each do |g|
@donation.gifts.build(g)
end

if @donation.save

end
end

Or something like that.

Franz Obenhauser wrote:

Thanks. Is there some way to manipulate the @params info so that ruby
automates this process?

On Jan 29, 1:21 pm, Chris O. [email protected]

I think I could explain this if I had to, but let me send you someplace
better first and if that doesn’t help come back. Railscasts had three
excelent screen casts on doing exactly what your asking about, and they
will be much better then a text answer I could write in the next 3
minutes.

Complex forms often lead to complex controllers, but that doesn’t have
to be the case. In this episode see how you can create multiple models
through a single form while keeping the controller clean.

See how to use Javascript and RJS to add and remove form fields
dynamically. This episode will build upon the previous episode allowing
you to create any number of tasks in one form the same time a project is
created.

In this third and final episode on complex forms [he] will show you how
to edit a project and multiple tasks all in one form. This includes
removing and adding tasks dynamically as well.