简体   繁体   English

:selected与rails形式的collection_select一起使用时不起作用

[英]:selected is not working when used with collection_select in rails form

I am trying to use :selected attribute in order to preset the value in the form .Unfortunately its getting to set to blank value . 我试图使用:selected属性以预设表单中的值。不幸的是,它被设置为空白值。

 <div class="field">
    <%= form.label :discrepancy_id, 'Failure Category' %>
    <%= form.collection_select :discrepancy_id, Discrepancy.group(:category), :id, :category, {:selected => (Discrepancy.all.select('id').where("category LIKE 'AVOD%'").first)}, :class => 'failure-category', :required => true%>
  </div>

The query works fine in rails console: 该查询在Rails控制台中运行良好:

Discrepancy.all.select('id').where("category LIKE 'AVOD%'").first

It doesnot work with :selected attribute . 它不适用于:selected属性。 Note : If I specify the id value (ie :selected = > 1 ) works fine but (:selected => Discrepancy.all.select('id').where("category LIKE 'AVOD%'").first) not working I dont undertand whats going wrong? 注意:如果我指定id值(即:selected => 1)可以正常工作,但是(:selected => Discrepancy.all.select('id')。where(“ category LIKE'AVOD%'”)。first)不能工作,我不了解发生了什么问题? Please let me know 请告诉我

This line returns an object, just because you use select the id doesn't change the fact that you get an object back. 这行代码返回一个对象,只是因为您使用select id并不会改变您返回对象的事实。

Discrepancy.all.select('id').where("category LIKE 'AVOD%'").first

you however need just the id 但是,您只需要ID

Discrepancy.where("category LIKE 'AVOD%'").first.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM