On Oct 13, 4:38 pm, Daniel <[EMAIL PROTECTED]> wrote:
> I am a newbie of ruby on rails. And I have met a problem with model
> association.
>
> I have 2 tables here, one is "item" the other is "brand", when I
> create one new item, I want to select one brand from the list.
>
> Here are the models:
>
> class Brand < ActiveRecord::Base
>   has_many :items
> end
>
> class Item < ActiveRecord::Base
>   belongs_to :brand
> end
>
> for item/new view
> <% form_for(@item) do |f| %>
>   <%= f.error_messages %>
>
>   <p>
>     <%= f.label :Brand %><br />
>     <%= f.collection_select(:brand, Brand.find(:all), :id, :name,
> {:prompt => "please select one brand"}) %>

I sometimes find these helper methods quite confusing.  The key is
what parameters they are sending back to your controller when you hit
the create button.
Check your logs if you're unsure.
The above line is probably sending
  params[:item][:brand] => <brand-id>
where <brand-id> is the id number for an existing brand.
Another way to check is to look at the generated select tag; it will
probably be <select name="item[brand]" ...>  (note how 'params' builds
its hash structure off the 'name' attribute).

You might want to change it to:
     <%= f.collection_select(:brand_id, Brand.find(:all), :id, :name,
 {:prompt => "please select one brand"}) %>

It depends on what your 'create' controller is doing; I assume you're
just instantiating a new item object and passing over the field values
from 'params'.  So if your object sees params[:item][:brand_id] you
might get what you want - the <brand-id> will be inserted into the
items.brand_id field.  If it sees 'brand' as per the original, then
I'm guessing it's trying to build the assocation via the Item#brand
association method which probably expects a Brand object and not its
id (in string form).

I always have to go back and check the docs.  So what I've said above
might not be totally right.  Get to know how 'params' is generated.
Writing stuff test-first on your functional tests will start you
thinking like this too.

Daniel
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to