I use Simple_form in my Rails 4 application.
How can I display error messages in a view that is not tied to a model ?
I want to have the same result than in other views based on models.
For now, this is the code in the view :
<%= simple_form_for(:registration, html: { role: 'form' }, :url => registrations_path) do |f| %>
<%= f.error_notification %>
<%= f.input :name, :required => true, :autofocus => true %>
<%= f.input :email, :required => true %>
<%= f.input :password, :required => true %>
<%= f.input :password_confirmation, :required => true %>
<%= f.button :submit %>
<% end %>
In a 'normal' view (i.e. with a model) the line <%= f.error_notification %> display errors.
What should I do in my controller to initialize something used by Simple_form to display errors ?
Thanks
The
simple_form_forhelper must wrap a model. But just because we say this doesn't mean it has to be an ActiveRecord model that's backed by a database table. You're free to create models that aren't backed by a database. In Rails 3+ the way to do this is to have your class include the components that you need fromActiveModel. This SO post explains how to do this with an example (and I'm sure there's many others out there). Once you have a model that includesActiveModel::Validationyou can add to theerrorscollection and then thef.error_notificationstatement will output the errors as you're used to in table-backed models.TL;DR: Create a non-ActiveRecord, non-table-backed model then treat it like a regular old model and the form should do the right thing.