Note that there are some explanatory texts on larger screens.

plurals
  1. POChecking for nil in view in Ruby on Rails
    primarykey
    data
    text
    <p>I've been working with Rails for a while now and one thing I find myself constantly doing is checking to see if some attribute or object is nil in my view code before I display it. I'm starting to wonder if this is always the best idea.</p> <p>My rationale so far has been that since my application(s) rely on user input unexpected things can occur. If I've learned one thing from programming in general it's that users inputting things the programmer didn't think of is one of the biggest sources of run-time errors. By checking for nil values I'm hoping to sidestep that and have my views gracefully handle the problem.</p> <p>The thing is though I typically for various reasons have similar nil or invalid value checks in either my model or controller code. I wouldn't call it code duplication in the strictest sense, but it just doesn't seem very DRY. If I've already checked for nil objects in my controller is it okay if my view just assumes the object truly isn't nil? For attributes that can be nil that are displayed it makes sense to me to check every time, but for the objects themselves I'm not sure what is the best practice.</p> <p>Here's a simplified, but typical example of what I'm talking about:</p> <p>controller code </p> <pre><code>def show @item = Item.find_by_id(params[:id]) @folders = Folder.find(:all, :order =&gt; 'display_order') if @item == nil or @item.folder == nil redirect_to(root_url) and return end end </code></pre> <p>view code</p> <pre><code>&lt;% if @item != nil %&gt; display the item's attributes here &lt;% if @item.folder != nil %&gt; &lt;%= link_to @item.folder.name, folder_path(@item.folder) %&gt; &lt;% end %&gt; &lt;% else %&gt; Oops! Looks like something went horribly wrong! &lt;% end %&gt; </code></pre> <p>Is this a good idea or is it just silly?</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.
 

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