How to process collection_select in controller?

Hello everyone,

I am currently somewhat stuck figuring out an elegant solution to my following problem:

Let's say I have the following classes:

class Event < ActiveRecord::Base   belongs_to :reg_template, :class_name => "EmailTemplate"   [...] end

class EmailTemplate < ActiveRecord::Base   has_many :events   [...] end

And a view that contains:

<%= f.collection_select(:reg_template_id, EmailTemplate.all, :id, :name) %>

What is the recommended way of processing this form field in an action controller?

Having a 1:1 relationship between Event and EmailTemplate means that Rails does not generate a reg_template_id and reg_template_id= method (as it would do for a 1:n relationship), so attempts to read or assign this field will fail with:   unknown attribute: reg_template_id when attempting to call   Event.update_attributes

Using <%= f.collection_select(:reg_template, EmailTemplate.all, :id, :name) %> instead also does not help much as it will fail with:   EmailTemplate(#70070455907700) expected, got String(#70070510199800)

I guess I must be missing something terribly obvious as I think is is rather common to update a model instance with a reference to another object through a collection_select.

Thanks & kind regards, Thilo

Hello Thilo,

In my opinion, there is nothing wrong with your piece of code. Are you sure you have a reg_template_id column in your table ? Could you show us the migration for the Event class ?

use this

<%= collection_select(:book, :subject_id,
                         @subjects, :id, :name) %>

some thing like this or

<h1>Edit Book Detail</h1>

<% form_tag :action => 'update', :id => @book do %>
<p><label for="book_title">Title</label>:
<%= text_field 'book', 'title' %></p>
<p><label for="book_price">Price</label>:

<%= text_field 'book', 'price' %></p>
<p><label for="book_subject">Subject</label>:
<%= collection_select(:book, :subject_id,
                         @subjects, :id, :name) %></p>

<p><label for="book_description">Description</label><br/>
<%= text_area 'book', 'description' %></p>
<%= submit_tag "Save changes" %>

<% end %>
<%= link_to 'Back', {:action => 'list' } %>

its just an idea

<%= f.collection_select(:reg_ template_id, EmailTemplate.all, :id, :name) %>

Hello Gael,

In my opinion, there is nothing wrong with your piece of code. Are you sure you have a reg_template_id column in your table ? Could you show us the migration for the Event class ?

sorry for the delayed response - some unexpected events got in my way...

Back to the topic: Well, I had manually added the column to the database table in addition to creating the corresponding migration and apparently missed that the column is supposed to be named reg_template_id and not just reg_template.

With the right column naming everything started working as expected.

Sorry for the confusion and thanks for your hint!

Thanks, Thilo