Search code examples
ruby-on-railsrubyruby-on-rails-5simple-formsimple-form-for

Translating form_for syntax to simple_form syntax


I have this code within my rails form:

  Categories: <%= f.collection_select :tag_ids, Tag.order(:name), :id, :name, {}, {multiple: true} %>

This code is working, but I want to use simpleform gem to redesign my form. However, I cannot seem to figure how to 'translate' this code into simple form. Anyone have any idea how? Thanks.


Solution

  • Something like this should do the trick:

    If you have a many to many relation you could first try what the default does.

    <%= f.association :tags %>
    

    If the defaults don't work out you can make an explicit collection:

    <%= f.input :tag_ids, as: :select, collection: Tag.order(:name), label_method: :name, input_html: {multiple: true} %>
    # or
    <%= f.input :tag_ids, as: :select, collection: Tag.order(:name).pluck(:name, :id), input_html: {multiple: true} %>
    

    Alternatively if you define the Tag#to_label method you don't have to pass the name of the label method. The Tag#id gets used as default value method. If you would like another value specify the method like so: value_method: :something_else.

    See the simple_form Usage section (intro, collections and associations).