如何显示单选按钮集合的选中值
How to display checked value for radio button collection
关于 Rails 5 和 collection_radio_buttons
的问题。
当您尝试编辑表单时,如何让它显示单选输入的选中值?
<%= collection_radio_buttons(:post, :category_id, Category.all, :id, :name) do |b| %>
<div class="radio">
<%= b.label do %>
<%= b.radio_button + b.text %>
<% end %>
</div>
<% end %>
使用 select 框 f.collection_select
它会记住该值但不使用 collection_radio_buttons
我的路由文件如下
路线
资源:帖子,如::条目
collection_radio_buttons
将自动设置所选值。
它从前两个参数中找到选定的值。就像在您的示例中一样,它将查找 @post.category_id
从该方法返回的任何值,它将查找值等于该值的相应单选按钮,并将该单选按钮设置为选中状态。
请查看 API DOCK 以获取完整文档。
如果设置的值不正确,请确保为您正在编辑的post
设置了category_id
这样就可以了。
<%= collection_radio_buttons(:post, :category_id, Category.all, :id, :name,{},{ checked: Category.first.id }) do |b| %>
<div class="radio">
<%= b.label do %>
<%= b.radio_button + b.text %>
<% end %>
</div>
<% end %>
我想通了。
这是因为我直接使用 collection_radio_buttons
而不是使用表单助手对象。
来自(不存储用户值)
<%= collection_radio_buttons(:post, :category_id, Category.all, :id, :name) do |b| %>
<div class="radio">
<%= b.label do %>
<%= b.radio_button + b.text %>
<% end %>
</div>
<% end %>
至(正在保存用户值)
# Using the form helper `f.collection_radio_buttons`
# instead of `collection_radio_buttons`.
# Also removed passing the object in as an argument
<%= f.collection_radio_buttons(:category_id, Category.all, :id, :name) do |b| %>
<div class="radio">
<%= b.label do %>
<%= b.radio_button + b.text %>
<% end %>
</div>
<% end %>
我希望这对以后的任何人都有帮助。
谢谢
关于 Rails 5 和 collection_radio_buttons
的问题。
当您尝试编辑表单时,如何让它显示单选输入的选中值?
<%= collection_radio_buttons(:post, :category_id, Category.all, :id, :name) do |b| %>
<div class="radio">
<%= b.label do %>
<%= b.radio_button + b.text %>
<% end %>
</div>
<% end %>
使用 select 框 f.collection_select
它会记住该值但不使用 collection_radio_buttons
我的路由文件如下
路线
资源:帖子,如::条目
collection_radio_buttons
将自动设置所选值。
它从前两个参数中找到选定的值。就像在您的示例中一样,它将查找 @post.category_id
从该方法返回的任何值,它将查找值等于该值的相应单选按钮,并将该单选按钮设置为选中状态。
请查看 API DOCK 以获取完整文档。
如果设置的值不正确,请确保为您正在编辑的post
设置了category_id
这样就可以了。
<%= collection_radio_buttons(:post, :category_id, Category.all, :id, :name,{},{ checked: Category.first.id }) do |b| %>
<div class="radio">
<%= b.label do %>
<%= b.radio_button + b.text %>
<% end %>
</div>
<% end %>
我想通了。
这是因为我直接使用 collection_radio_buttons
而不是使用表单助手对象。
来自(不存储用户值)
<%= collection_radio_buttons(:post, :category_id, Category.all, :id, :name) do |b| %>
<div class="radio">
<%= b.label do %>
<%= b.radio_button + b.text %>
<% end %>
</div>
<% end %>
至(正在保存用户值)
# Using the form helper `f.collection_radio_buttons`
# instead of `collection_radio_buttons`.
# Also removed passing the object in as an argument
<%= f.collection_radio_buttons(:category_id, Category.all, :id, :name) do |b| %>
<div class="radio">
<%= b.label do %>
<%= b.radio_button + b.text %>
<% end %>
</div>
<% end %>
我希望这对以后的任何人都有帮助。
谢谢