【问题标题】:How to Change Label Name Attribute in simple_fields_for如何在 simple_fields_for 中更改标签名称属性
【发布时间】:2014-06-04 13:36:52
【问题描述】:

我正在为多个多态模型、Trip 和 Service 创建一个评级表单,它们都公开了 Rateable mixin,它带来了一个关联 has_many :ratings。为了提交单个表单,我将两个多态模型合并为一个代理,然后遍历代理以使用 simple_fields_for 创建表单。

因为表单是针对 Rateable obj 上的 Rating 对象,simple_form 创建了一系列字段,但名称都是“ratings[value]”、“ratings[cmets]”等。为了解决这个问题,我使用了 @987654323 @参数我找到了here,修复了名称问题,如下图。但是标签也没有改变,而且我不知道如何告诉 SimpleForm 使用 index 参数来更改标签的 for 属性。

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 参数,希望它能够更新标签和输入,但它似乎没有这样做。 如何更改标签指向的位置,使其指向具有新名称的输入

【问题讨论】:

    标签: ruby-on-rails simple-form


    【解决方案1】:

    我最终通过将ratings_form.input :value, as: :radio_buttons 替换为ratings_form.collection_radio_buttons 解决了这个问题

    【讨论】:

    • 作为后续,我从未发现任何方法可以控制标签的 for 简单形式的属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    相关资源
    最近更新 更多