【问题标题】:Force Rails to assign nil value also using simple_form强制 Rails 也使用 simple_form 分配 nil 值
【发布时间】:2021-11-08 13:16:35
【问题描述】:

我在网页中有一个用例,除了 true 和 false 之外,我还需要有“nil”值。 我已经像下面那样实现了它,但是当我在 GUI 中选择“未选中”时,它总是跳到“是”(真)。 有没有强制 Rails 也分配 nil 值?

代码:

f.input :confirmed, label: 'Confirmed', as: :radio_buttons, collection: [[ true, "Yes" ], [ false, "No" ], [ nil, "unchecked"]], label_method: :second, value_method: :first, selected: [ nil, 'unchecked' ]

【问题讨论】:

  • 您确定没有为数据库中的列设置默认值吗?您能否发布表单传递的参数和其他相关代码,例如控制器和模型是否需要?

标签: ruby-on-rails ruby simple-form


【解决方案1】:

你可以试试collection_radio_buttons:

<%= f.collection_radio_buttons(:confirmed, [[true, 'Yes'], [false, 'No'], [nil, 'unchecked']], :first, :second,{ checked: [nil, 'unchecked'] }) do |b| %>
  <% b.label do %>
    <%= b.radio_button %> <%= b.text %>
  <% end %>
<% end %>

【讨论】:

  • 谢谢,我试过了,但我有同样的问题。在数据库中,'nil' 值未保存。 When pick the 'unchecked' I press the submit button it gives me the success message but I if I search in the database the 'nil' value is not saved, the value that is saved is 'true'.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-04
  • 1970-01-01
相关资源
最近更新 更多