Rails polymorphic 关联的 model, 在 form 中如何写成 select tag

hardywu · 2014年02月19日 · 最后由 hardywu 回复于 2014年02月19日 · 2148 次阅读

如题

class apple  < ActiveRecord::Base
  belongs_to :dinner, as: :fruit
end

class peach < ActiveRecord::Base
  belongs_to :dinner, as: :fruit
end

class dinner < ActiveRecord::Base
  has_many :fruits, polymorphic: true
  accepts_nested_attributes_for :fruits
end

如果我想 create 一个 dinner record, 希望能有一个

= form_for @dinner do |f|
  = f.field_for :fruit do |p|
    = p.text_field :fruit_id
    = p.text_field :fruit_type

  = f.submit

总不能让用户填写 id 和 class 名,有什么最好的办法把上面的两个 text_field 换成一个 select tag?

共收到 2 条回复

3.1 The Select and Option Tags The most generic helper is select_tag, which — as the name implies — simply generates the SELECT tag that encapsulates an options string:

<%= select_tag(:city_id, 'Lisbon...') %> This is a start, but it doesn't dynamically create the option tags. You can generate option tags with the options_for_select helper:

<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>

output:

Lisbon Madrid ... The first argument to options_for_select is a nested array where each element has two elements: option text (city name) and option value (city id). The option value is what will be submitted to your controller. Often this will be the id of a corresponding database object but this does not have to be the case.

Knowing this, you can combine select_tag and options_for_select to achieve the desired, complete markup:

<%= select_tag(:city_id, > options_for_select(...)) %> options_for_select allows you to pre-select an option by passing its value.

<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>

output:

Lisbon selected="selected">Madrid ... Whenever Rails sees that the internal value of an option being generated matches this value, it will add the selected attribute to that option.

查看全文

#1 楼 @cassiuschen 这里貌似也是一次只能生产对单一 attribute 的 select tag

需要 登录 后方可回复, 如果你还没有账号请点击这里 注册