Allows you to make really simple non-persisted form objects or models.
Only suitable for Rails 4 applications.
You don't need to remember to:
- Set the class
model_nameso Rails url generation works for forms.
It gives you:
- Default values for your form attributes.
- Integration with simple_form so you don't need to specify the field type on the form.
- Thanks to
ActiveModel::Modelyou can use standard Rails validations on your attributes.
Add this line to your application's Gemfile:
And then execute:
Create a form class. I like to put them inside
app/forms/. If you
prefer to create models then that will work too.
class PostForm include SimpleFormObject attribute :body, :text attribute :title, :string attribute :publish_date, :datetime, default: Time.now validates_presence_of :body validates_presence_of :title end
ActiveModel::Model so you don't need to.
It also intelligently sets the
model_name on the class so that Rails
routing works as expected. As an example:
<%= simple_form_for @post_form do |f| %> <%= f.input :title # renders a simple string input %> <%= f.input :body # renders a textarea %> <%= f.input :publish_date # renders a datetime select html element %> <% end %>
Will create a HTML form which will
posts_path. In your controller, you can do something like this:
def new @post_form = PostForm.new end def create @post_form = PostForm.new(param[:post]) if @post_form.valid? # save the data flash[:notice] = "Post created successfully." # redirect somewhere else flash[:error] = @post_form.errors.full_messages render 'new' end end
- Automatically add good validations for types.
- It's tested in
specbut better tests wouldn't hurt.
- Fork it ( http://github.com/reInteractive-open/simple_form_objects/fork )
- 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