Note that there are some explanatory texts on larger screens.

plurals
  1. PORails: rendering a collection after an object in that collection fails validation
    primarykey
    data
    text
    <p>Let's say I have the following models</p> <p><strong>models/user.rb</strong></p> <pre><code>class User has_many :degrees end </code></pre> <p><strong>models/degree.rb</strong></p> <pre><code>class Degree attr_accessible :name belongs_to :user validates :name, :presence =&gt; true end </code></pre> <p>Within <code>Users#show</code> I want to display the users degrees and provide a form for creating a new one.</p> <p><strong>views/users/show.html.erb</strong></p> <pre><code>... Your current degrees: &lt;%= render @user.degrees %&gt; Add a new degree: &lt;%= form_for Degree.new do |f| %&gt; &lt;%= f.text_field :name %&gt; &lt;%= f.submit "Submit" %&gt; &lt;% end %&gt; ... </code></pre> <p><strong>views/degrees/_degree.html.erb</strong></p> <pre><code>... &lt;%= degree.name %&gt; </code></pre> <p>So inside degrees_controller.rb we have</p> <p><strong>controllers/degrees_controller.rb</strong></p> <pre><code>class DegreesController &lt; ApplicationController # ... def create degree = current_user.degrees.build(params[:degree]) if degree.save redirect_to # somewhere with a flash message else render "users#show" end end end </code></pre> <p>The problem with this is in the call to <code>render @user.degrees</code> inside <code>views/users/show.html.erb</code> after a degree has failed validation. If I submit the form without providing a name, the degree object persists in memory after the <code>render</code> method is called, and will render the <code>views/degrees/_degree.html.erb</code> partial for the invalid object. This partial calls the <code>name</code> method, which throws a Nil error.</p> <p>I can throw conditionals in the view (i.e., <code>unless degree.name.nil?</code>), but this smells to me. If the attributes on the degree object grow, that partial will contain way too much conditional logic.</p> <p>Any thoughts?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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