views:

42

answers:

1

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.

A: 

If you have the column reg_template_id in the events table, then the following code should work:

<%= f.collection_select(:reg_template_id, EmailTemplate.all, :id, :name) %>
KandadaBoggu
The foreign key in the events table is named `reg_template_id`, but unfortunately using it yields the `unknown attribute: reg_template_id` error I mentioned above. Would changing its name to `email_template_id` change anything about the situation?
tg
The foreign key `reg_template_id` should work. What happens when you create an instance of Event object and access `reg_template_id`? i.e. `Event.new.reg_template_id`
KandadaBoggu
Did you run all migrations yet?
nanda
Well, seems I had manually added the column with the wrong name (while it was correctly named in the migration). Sorry for the confusion!
tg