在
Ruby on Rails中制作与某个问题相关的复选框的正确方法是什么?现在我有:
<div class="form_row"> <label for="features[]">Features:</label> <br><%= check_Box_tag 'features[]','scenarios' %> Scenarios <br><%= check_Box_tag 'features[]','role_profiles' %> Role profiles <br><%= check_Box_tag 'features[]','private_messages' %> Private messages <br><%= check_Box_tag 'features[]','chatrooms' %> Chatrooms <br><%= check_Box_tag 'features[]','forums' %> Forums <br><%= check_Box_tag 'features[]','news' %> News <br><%= check_Box_tag 'features[]','polls' %> Polls </div>
我也想能够自动检查先前选择的项目(如果此表单被重新加载).我将如何将参数加载到这些默认值?
解决方法
您正在查看以下内容:
<div class="form_row"> <label for="features[]">Features:</label> <% [ 'scenarios','role_profiles',...,'polls' ].each do |feature| %> <br><%= check_Box_tag 'features[]',feature,(params[:features] || {}).include?(feature) %> <%= feature.humanize %> <% end %> </div>
虽然如果您已经拥有Feature模型,功能表和has_many:features关系,您可能希望这样做:
<div class="form_row"> <label for="feature_ids[]">Features:</label> <% for feature in Feature.find(:all) do %> <br><%= check_Box_tag 'feature_ids[]',feature.id,@model.feature_ids.include?(feature.id) %> <%= feature.name.humanize %> <% end %> </div>