如何在simple_fields_for中更改标签名称属性

时间:2014-06-04 13:36:53

标签: ruby-on-rails simple-form

我正在为许多多态模型Trip和Service创建一个评级表,这两个模型都暴露了Rateable mixin,它引入了一个关联has_many :ratings。为了提交单个表单,我将两个多态模型聚合到一个代理中,然后迭代代理以使用simple_fields_for创建表单。

因为表格是针对Rateable obj的评级对象,所以simple_form创建了一系列字段,但名称都是&#34;评级[值]&#34;,&#34;评分[评论]&#34 ;为了解决这个问题,我使用了index参数here来修复名称问题,如下所示。但是,标签也没有变化,我也不知道如何告诉SimpleForm使用index参数来更改标签的for属性。< / p>

RatingsProxy.rb
  attr_reader :rateables # A simple array of different types of Models
end

module Rateable
  has_many :ratings, as: :rateable
  accepts_nested_attributes_for :ratings
end

= simple_form_for @ratings_proxy do |f|
  - @ratings_proxy.rateables.each do |rateable|
    = simple_fields_for :ratings, rateable.ratings.build, index: rateable.class.name do |ratings_form|
      = ratings_form.input :value, as: :radio_buttons
        = ratings_form.input :comments

现在,我输入的HTML看起来像这样:

<!-- Created by one rateable model, Trip.  Note the name attribute on the label vs. input -->
<label for="ratings_Trip_value_5" name="ratings[value]">
  <input class="radio_buttons required" id="ratings_Trip_value_5" name="ratings[Trip][value]" type="radio" value="5">
  5
</label>
...
<!-- Created by a different rateable model, Service -->
<label for="ratings_value_5" name="ratings[value]">
  <input class="radio_buttons required" id="ratings_Service_value_5" name="ratings[Service][value]" type="radio" value="5">
  5
</label>

我在simple_fields_for上添加了index参数,期望它更新标签和输入,但它似乎没有这样做。 如何更改标签指向的位置,以便指向具有新名称的输入

1 个答案:

答案 0 :(得分:1)

我最终通过将ratings_form.input :value, as: :radio_buttons替换为ratings_form.collection_radio_buttons

来解决此问题