开发者

Elegant way to process collection_select in controller?

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.


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) %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜