Forum: Ruby on Rails select helper question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Daniel Völkerts (Guest)
on 2006-04-09 19:40
(Received via mailing list)
Hi there, I try to develop a medical application using ruby on rails.

There are many categories which can contain subcategories.

I defined the model like this:

class Category < ActiveRecord::Base
	has_and_belongs_to_many :notes


	belongs_to :parent_category, :class_name=>"Category",
:foreign_key=>"category_id"
	has_many :sub_categories, :class_name=>"Category",
:foreign_key=>"category_id"

end

And scaffolded the controller with the generator. I modified the
_form.rhtml for creating and updated to this:

<%= error_messages_for 'category' %>

<!--[form:category]-->


<p><label for="category_name">Name</label><br/>
<%= text_field 'category', 'name'  %></p>
<p>Abspeichern unter:<br/>
<%= select 'category','parent_category', Category.find_all.collect {|p|
[p.name,p.id]} %></p>
<!--[eoform:category]-->


I'd like that the select tag contained all categories. After I commit
the form, I've got a

ActiveRecord::AssociationTypeMismatch in Admin#update

Category expected, got String

exception as the params[:category][:parent_category] contains a number,
not a object of Category.

I have fixed this ad hoc by adding

params[:category][:parent_id] =
Category.find(params[:category][:parent_id])

in the action methods in the controller before the


Category.new(params[:category]) or the
@category.update_attributes(params[:category])

are called.

How can I modify the select helper to display the name of the object an
pass the object to the params hash directly?


TIA,
Mark Reginald J. (Guest)
on 2006-04-10 16:48
(Received via mailing list)
Daniel Völkerts wrote:

> class Category < ActiveRecord::Base
>     has_and_belongs_to_many :notes
>     belongs_to :parent_category, :class_name=>"Category", :foreign_key=>"category_id"
>     has_many :sub_categories, :class_name=>"Category", :foreign_key=>"category_id"
> end
>
> <%= select 'category','parent_category', Category.find_all.collect {|p| [p.name,p.id]} 
%></p>
>
> ActiveRecord::AssociationTypeMismatch in Admin#update
> Category expected, got String

Use the foreign key in the select helper directly:

<%= select :category, :category_id, ...

--
We develop, watch us RoR, in numbers too big to ignore.
This topic is locked and can not be replied to.