Search code examples
ruby-on-railsruby-on-rails-5

: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 .

 <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:

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

It doesnot work with :selected attribute . Note : If I specify the id value (i.e :selected = > 1 ) works fine but (:selected => Discrepancy.all.select('id').where("category LIKE 'AVOD%'").first) not working I dont undertand whats going wrong? Please let me know


Solution

  • This line returns an object, just because you use select the id doesn't change the fact that you get an object back.

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

    you however need just the id

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