ActiveModel lets you easily create objects that can be used in form helpers and even support round-tripping (assigning the submitted params again)
But ActiveModel doesn't support out of the box argument parsing, e.g. having a datetime attribute be a datetime attribute and a boolean attribute be a boolean attribute.
This fixes that.
Add this line to your application's Gemfile:
In the controller:
class FormsController < ApplicationController class SearchForm < :: self.model_name = 'q' # => <input name="q[username]" ... /> etc. attribute :username, :string attribute :created_at, :date_time attribute :locked, :boolean validates_presence_of :username validates_presence_of :created_at end def search @search = SearchForm.new(params[:q]) if @search.valid? @users = User.where(username: @search.username) # ... end end end
and the view:
<%= form_for @search, url: form_path do |f| %> <%= f.text_field :username %><br /> <%= f.datetime_select :created_at %><br /> <%= f.check_box :locked %><br /> <%= f.submit %> <% end %>
If you use
formtastic, they automatically create date_time or boolean inputs based on your form object.
Also check out the example project.
This gem doesn't hook into any Rails (or
internals and doesn't monkey patch anything, it only uses the ActiveModel API.
So it should be future proof.
- Fork it
- Create your feature branch (
git checkout -b my-new-feature)
- Commit your changes (
git commit -am 'Add some feature')
- Push to the branch (
git push origin my-new-feature)
- Create new Pull Request