Simple Form
Summary
GitHub
Manual
Common Scenarios
Drop down lists with associated models
The implementation of dropdown lists in Simple Form leverages the collection feature. Here are the changes that I made in my related model, controller and view
Model
class Stuff < ApplicationRecord
belongs_to :user, required: false
has_one :category
end
Controller
# GET /stuffs/new
def new
@stuff = Stuff.new
@categories = Category.all
end
View
<%= f.input :category_id, as: :select, collection: @categories %>
Overriding the default id
There are two common ways of overriding the default css id in Simple Form. The first way is just to assign it to an id
<%= f.input :category_name, id: 'category_name' %>
The other way is to override it with input_html
<%= f.input :bunch, collection: @bunches, input_html: { id: 'my_bunches_dropdown'} %>
Collection of checkboxes
Let's say you have a model of Posts that has a "has many" relationship with a model of comments and you wanted to create a form with checkboxes associated with those comments. Here's how you'd set it up
<%= simple_form_for(@post) do |f| %>
<table class="table">
<%= f.collection_check_boxes :commentss_list, @post.comments, :id, :name do |builder| %>
<tr>
<td><%= builder.check_box %></td>
<td><%= builder.label %></td>
<tr>
<% end %>
</table>
<% end %>
You can also customize the id of the checkboxes by doing the following:
<td><%= builder.check_box id: "comment_#{builder.object.id}_checkbox" %></td>