【问题标题】:Check_box and radio_button for form_helper in railsrails 中 form_helper 的 Check_box 和 radio_button
【发布时间】:2019-10-17 11:33:53
【问题描述】:

我浏览了 rails 的 rails 文档,但找不到任何地方可以提供有关 check_boxradio_button 的信息来处理模型对象。

    = f.radio_button(:recurring_status, true)
    = f.label :recurring_status, "Yes?"
    = f.radio_button(:recurring_status, false)
    = f.label :recurring_status_false, "No?"

我用radio_button 尝试过这个,但值只是没有从params 中的表单传递。与check_box 相同。

有人可以向我解释为什么会发生这种情况,以及为什么 rails 没有指定 check_boxradio_button 与模型对象一起使用。

还有,

<%= check_box_tag(:pet_dog) %>
<%= label_tag(:pet_dog, "I own a dog") %>
<%= check_box_tag(:pet_cat) %>
<%= label_tag(:pet_cat, "I own a cat") %>

<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
<label for="pet_dog">I own a dog</label>
<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
<label for="pet_cat">I own a cat</label>

这是官方文档中给出的示例,两个复选框的值都与“1”相同。很难理解这里发生了什么。

【问题讨论】:

    标签: ruby-on-rails ruby form-helpers


    【解决方案1】:

    https://api.rubyonrails.org/v5.1.7/classes/ActionView/Helpers/FormOptionsHelper.html 看看这个。

        collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial)
    
    =>     <input id="post_author_ids_1" name="post[author_ids][]" type="checkbox" value="1" checked="checked" />
           <label for="post_author_ids_1">D. Heinemeier Hansson</label>
           <input id="post_author_ids_2" name="post[author_ids][]" type="checkbox" value="2" />
           <label for="post_author_ids_2">D. Thomas</label>
           <input id="post_author_ids_3" name="post[author_ids][]" type="checkbox" value="3" />
           <label for="post_author_ids_3">M. Clark</label>
           <input name="post[author_ids][]" type="hidden" value="" />
    
        collection_radio_buttons(:post, :author_id, Author.all, :id, :name_with_initial)
    
    =>    <input id="post_author_id_1" name="post[author_id]" type="radio" value="1" checked="checked" />
          <label for="post_author_id_1">D. Heinemeier Hansson</label>
          <input id="post_author_id_2" name="post[author_id]" type="radio" value="2" />
          <label for="post_author_id_2">D. Thomas</label>
          <input id="post_author_id_3" name="post[author_id]" type="radio" value="3" />
          <label for="post_author_id_3">M. Clark</label>
    
        collection_select(:post, :category_id, Category.all, :id, :name, {disabled: -> (category) { category.archived? }})
    
    =>   <select name="post[category_id]" id="post_category_id">
         <option value="1" disabled="disabled">2008 stuff</option>
         <option value="2" disabled="disabled">Christmas</option>
         <option value="3">Jokes</option>`enter code here`
         <option value="4">Poems</option>
         </select>
    

    【讨论】:

      猜你喜欢
      • 2014-07-04
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      相关资源
      最近更新 更多