Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to carry over form field values after an invalid submit, using only ActiveModel?
    text
    copied!<p>It appears to be normal functionality for a Rails form that has been submitted with invalid data to display error messages and repopulate the form with the invalid data. At least, all my Active Record managed resources work this way.</p> <p>However, I have a virtual resource/model that is not an Active Record but instead makes use Rails 3 ActiveModel along the lines of <a href="http://railscasts.com/episodes/219-active-model" rel="nofollow">Railscast #219</a>.</p> <p>Everything works as I expect, apart from when submission fails. The re-rendered form is empty. Error messages are displayed as normal.</p> <p>Which part of Rails is responsible for this functionality and how do I include it in my ActiveModel based resource?</p> <p><strong>To clarify:</strong></p> <ol> <li>A user completes and submits a form containing two values.</li> <li>Validation fails because one or more of these values is invalid.</li> <li>The controller re-renders the 'new' view for the model.</li> <li>The re-rendered form contains error messages.</li> <li>The re-rendered form is pre-populated with the two invalid data values.</li> </ol> <p>It is step 5 that I do not understand and which is not happening with my Active Model resource, despite having near identical controller code and identical view code, to my Active Record resources.</p> <p><strong>The code</strong> (as requested)</p> <p>Controller:</p> <pre><code>def new @contact = Contact.new end def create @contact = Contact.new(params[:contact]) if @contact.valid? AgentMailer.contact_email(@contact).deliver redirect_to "/contact", notice: 'Your request was successful.' else #TODO Figure out why data from an invalid submission does not carry over render action: "new" end end </code></pre> <p>View:</p> <pre><code>&lt;%= form_for(@contact, :html =&gt; {:class =&gt; "new_contact custom"}) do |f| %&gt; &lt;% if @contact.errors.any? %&gt; ... &lt;% end %&gt; ... &lt;%= f.label :name %&gt; &lt;%= f.text_field :name, options = {placeholder: "Enter name here"} %&gt; ... &lt;% end %&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload