我有一个动作,呈现包含此内容的视图:
<select id ='dynamic_select'>
<option value = "<%= activity_path %>">All</option>
<option value = "<%= activity_path(:type => 'enrolled') %>">Enrolled</option>
<option value = "<%= activity_path(:type => 'redeem') %>">Redeem</option>
<option value = "<%= activity_path(:type => 'social') %>">Social</option>
</select>
根据类型参数,选择并标记为选定的一个选项的正确/ Rails方式是什么:
如果有无类型参数,请选择“全部”选项,如果 type =已注册参数选择已注册选项,依此类推......
我已经设法用Javascript做客户端,但我想知道Rails的做法是什么。
呈现HTML:
<select id="dynamic_select" name="dynamic_select">
<option value="/activity">All</option>
<option value="/activity?type=enrolled">Enrolled</option>
<option value="/activity?type=redeem">Redeem</option>
<option value="/activity?type=social">Social</option>
</select>
答案 0 :(得分:1)
如下所示。我在这里显示了select_options,但您应该在控制器中生成它们并将它们传递给视图。
关键是使用options_for_select。
<% select_options = {"All" => activity_path} %>
<% %w{Enrolled Redeem Social}.each {|opt| select_options[opt] = activity_path(:type => opt.downcase)} %>
<% form_for(resource) do |f| %>
<%= s.select :dynamic, options_for_select(select_option, :selected => select_options[@default || "All"]) %>
<% end %>