How to set current value in collection in simple_form

14,098

Assuming the active attribute for categories is a boolean, try:

:selected => (@category.active? ? 'Yes' : 'No')
Share:
14,098
user938363
Author by

user938363

learning rails with real project

Updated on July 19, 2022

Comments

  • user938363
    user938363 almost 2 years

    Here is a piece of code in edit.html.erb which does not work. The purpose of the code is to fill a form for editing. Collection is used with option of yes and no. How can I set the collection to the current 'active' value with :selected option?

    <%= simple_form_for @category do |f| %>
    
      <%= f.input :name, :disabled => true, :required => false %>  
      <%= f.input :description %> 
      <%= f.input :active, :collection => ['Yes', 'No'], :selected => f.active %> 
      <%= f.button :submit %>  
    <% end %>
    

    The error saying the active is not a method in f.input :active, :collection.

  • user938363
    user938363 over 12 years
    It did not work. The Active collection only show Yes, even the active is false. Thanks.
  • James
    James over 12 years
    Is the active attribute a boolean? It would make more sense for it to be a boolean, but if it's a string then try :selected => (@category.active == 'Yes' ? 'Yes' : 'No')
  • user938363
    user938363 over 12 years
    It works. Here is the code:<%= f.input :active, :collection => [['Yes', 1], ['No', 0]], :selected => (@category.active? ? 1 : 0)
  • karmi
    karmi over 9 years
    You can use a lambda as well: selected: lambda { |category| category.id == params[:category_id] }