【问题标题】:Adding new options to rails select/radio buttons/ checkboxes向 Rails 选择/单选按钮/复选框添加新选项
【发布时间】:2018-03-23 23:14:48
【问题描述】:

我有一个包含许多字段的表单,其中包含复选框和单选按钮。我希望在每个选项中添加一个“其他”选项。现在如果用户点击其他选项,他应该被允许添加应该保存在数据库中以供将来使用的新选项。

这是我当前的代码:

<label> Goals: </label><br>
<%= f.collection_check_boxes :goal_id, Admin::Goal.all, :id, :title, checked: @assessment.goal_id, :include_hidden => false do |b| %>
  <%= b.label class:"label-checkbox" do %>
   <%= b.check_box + b.text%>
  <% end %>
<% end %>

【问题讨论】:

  • 检查我的解决方案

标签: ruby-on-rails select checkbox radio-button


【解决方案1】:

您需要像这样自定义collection_check_box

<% other_options = [{id: "other",title: "other"}] %>

<label> Goals: </label><br>
<%= f.collection_check_boxes :goal_id, Admin::Goal.all + other_options, lambda{|a|a["id"]}, lambda{|a|a["title"], checked: @assessment.goal_id, :include_hidden => false do |b| %>
  <%= b.label class:"label-checkbox" do %>
   <%= b.check_box + b.object[:title]%>
  <% end %>
<% end %>

我在这里做什么:

  • 合并 other_option 数组和您的目标集合数组。
  • 其他数组不是关系,因此您需要修改获取 id、title 的方式。所以我使用 lambda 来访问它。
  • 如果您只使用目标,b.text 将起作用。由于我们使用的是自定义哈希,即 other_option 数组,我们需要将 value 作为 b.object 访问,然后访问 title。这对双方都有效。

【讨论】:

    猜你喜欢
    • 2011-07-19
    • 1970-01-01
    • 2018-11-06
    • 2018-12-06
    • 1970-01-01
    • 2016-04-03
    • 1970-01-01
    • 2013-04-18
    • 2012-12-14
    相关资源
    最近更新 更多