【问题标题】:Change the option selected on collection_select更改在 collection_select 上选择的选项
【发布时间】:2016-05-27 19:58:05
【问题描述】:

我正在尝试更改在我的 rails 表单上的 collection_select 上选择的选项。

我的代码如下所示:

<%= f.collection_select :course_type_id, CourseType.where(:deleted => false), :id, :name, {}, {class: 'form-control  m-b', :selected => @course_template.course_type.name } %>

但是,选择的选项始终显示第一个并且永远不会改变,除非用户选择不同的选项。

生成的 html 如下所示:

<select class="form-control  m-b" selected="selected" name="course[course_type_id]" id="course_course_type_id">
    <option value="1">Driving</option>
    <option value="2">Pratical</option>
</select>

关于我做错了什么有什么想法吗?

【问题讨论】:

  • @course_template.course_type.name 的值是多少?
  • @course_template.course_type.name 的值在这种情况下是Pratical
  • 你能试试:selected =&gt; @course_template.course_type.id吗?
  • 我也试过像&lt;%= f.collection_select :course_type_id, CourseType.where(:deleted =&gt; false), :id, :name, {}, {class: 'form-control m-b', selected: @course_template.course_type.id } %&gt;这样的id,但结果是一样的。
  • 请尝试:&lt;%= f.collection_select :course_type_id, CourseType.where(:deleted =&gt; false), :id, :name, { :selected =&gt; @course_template.course_type.id }, {class: 'form-control m-b' } %&gt;

标签: ruby-on-rails forms


【解决方案1】:

看起来您正在将 :selected 键放入 html_options 参数属性中。

Here is the method definition for collection_select:

collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})

试试这个:

<%= f.collection_select :course_type_id, CourseType.where(:deleted => false), :id, :name, {:selected => @course_template.course_type.name}, {class: 'form-control  m-b' } %>

【讨论】:

    【解决方案2】:

    &lt;%= f.collection_select :course_type_id, CourseType.where(:deleted =&gt; false), :id, :name, { :selected =&gt; @course_template.course_type.id }, {class: 'form-control m-b' } %&gt;

    1. selected 参数采用value,而不是选项的name
    2. collection_select 定义来看,selected 选项和html_options 是不同的参数。

    如需进一步了解,请参考here

    【讨论】:

      猜你喜欢
      • 2016-09-28
      • 2014-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      相关资源
      最近更新 更多