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>
Nested models inside of a form
Nested Models let you build forms that update an object and its associated objects all in one shot.
Models are setup the following way
class Person < ApplicationRecord
has_many :person_contracts
has_many :contracts, through: :person_contracts
end
class PersonContract < ApplicationRecord
belongs_to :person
belongs_to :contract
accepts_nested_attributes_for :contract
end
class Contract < ApplicationRecord
has_many :person_contracts
end
Controllers are setup the following way
def new
@person_contract = PersonContract.new
@person_contract.build_contract
end
View is setup this way
<%= simple_form_for(@person_contract) do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
Contract Information
<%= f.simple_fields_for :contracts do |contract_form| %> <%= f.input :contract_value %> <% end %>
<% end %>