Rails 循环生成 radio 的问题

d4rkl0rd · 2012年01月16日 · 最后由 metal 回复于 2012年02月04日 · 3952 次阅读

我的 radio 数据来自数据库码表,想问下,比如我循环生成 radio_button 后,如何设置某一个为默认选中呢? <% xx.each{...%> <%=radio_button xxx%> <%}%> 这样都不是选中的,如何设置某一个选中呢?谢谢

这种问题是要看 Rails 文档的,你应该 google 一下,http://www.google.com.hk/search?sourceid=chrome&ie=UTF-8&q=radio_button

然后第一个链接中就有答案:http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-radio_button

To force the radio button to be checked pass :checked => true in the options hash.

问题是,这样的话,每个 radio 都有个 checked,比如我只想指定某一个为 checked 如何呢?在 php 中,可以加代码进行判断,如果等于某个元素那么就加上 checked,不知道 rails 中行不,如果用 radio_button

#2 楼 @d4rkl0rd 你也可以代码判断啊

<% xx.each do |value|%>
    <% if condition %> 
        <%=radio_button xxx,:checked => true%> 
    <% else %>
        <%=radio_button xxx%> 
    <% end %>
<%end%> 

view 中太多逻辑,应该提取为 helper

这个我做过。给你一个参考一下吧。

http://stackoverflow.com/questions/4708910/rails-how-to-make-a-conditional-radio-button-checked

<%= radio_button_tag 'permission[role_id]', '2', !!(@permission.role_id.nil? || @permission.role_id == 2) %>
需要 登录 后方可回复, 如果你还没有账号请 注册新账号