【问题标题】:Default radio button with scope in model?模型中具有范围的默认单选按钮?
【发布时间】:2016-02-11 17:42:11
【问题描述】:

One-Shot 成为默认单选按钮选择的最佳方法是什么?

_form

<% Challenge::CATEGORY.each do |c| %>&nbsp;
  <span class="label label-primary"> <%= label(c, c) %> </span>
  <%= f.radio_button(:category, c, :class => "date-format-switcher") %>
<% end %>

<div id='id_of_first_div'>
  One-Shot
</div>

<div id='id_of_second_div'>
  Ongoing
</div>

<script>
$(function(){
  $('#challenge_category_one-shot').click(function(){ $('#id_of_first_div').show(); $('#id_of_second_div').hide(); });
  $('#challenge_category_ongoing').click(function(){ $('#id_of_first_div').hide(); $('#id_of_second_div').show(); });
});
</script>

challenge.rb

scope :oneshot,  -> { where(categories: 'One-Shot') }
scope :ongoing,  -> { where(categories: 'Ongoing') }
CATEGORY = ['One-Shot', 'Ongoing']

架构

t.string   "category"

【问题讨论】:

    标签: ruby-on-rails ruby model-view-controller scope radio-button


    【解决方案1】:

    如果你打算使用 f.radio_button 那么你可以添加参数

    checked: (c=='One-Shot')
    

    您也可以改用 r.collection_radio_buttons:

    <% categories = ['One-Shot', 'Ongoing'] %>                                    
    <%= f.collection_radio_buttons :category, categories, :to_s, :to_s, {checked: 'One-Shot'} %>
    

    【讨论】:

    • 再次感谢!我尝试了您的两种解决方案,它们在将默认值设置为One-Shot 时效果很好,但是解决方案与我发布的最后一个问题产生了问题,您帮助我解决了:] 即当页面加载时仍然显示:@ 987654324@ 和&lt;div id='id_of_second_div'&gt; 而不是只显示与One-Shot 相关的&lt;div id='id_of_first_div'&gt;。你知道我的意思?如果您愿意,我可以发布一个新问题
    • 将另一个 $('#id_of_div_you_want_to_hide').hide() 添加到 onready 函数 ($(function(){ ... }) 中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2017-10-02
    • 2017-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多