Select helper question

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’ %>

Name
<%= text_field 'category', 'name' %>

Abspeichern unter:
<%= select 'category','parent_category', Category.find_all.collect {|p| [p.name,p.id]} %>

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,

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]} %>

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.