Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm going to echo what the other two have said. The survey you are trying to reference is <code>nil</code>, and <code>nil</code> does not have a method called <code>contact</code>. I am going to offer up a slightly different solution:</p> <pre><code>def create_permitted? acting_user == survey.try(:contact) or acting_user.administrator? end </code></pre> <p>The <code>#try</code> method exists on <code>nil</code> and on <code>survey</code>. It basically wraps the method call in a <code>rescue</code>. Conceptually, it looks like:</p> <pre><code>def try(method_name, *args) self.send(method_name, args) rescue nil end </code></pre> <p>This may reduce the amount of code that you have to write to catch conditions where a relationship may not be present, preventing a <code>NoMethodError</code> exception.</p> <p><code>#try</code> is part of the Rails core extensions for <code>Object</code>. In reality, it does not work as I have above, since exceptions arising from calls to <code>Object#try</code> will still happen as they normally should. Instead, it extends <code>Object</code> by calling <code>send</code>. It extends <code>NilClass</code> by returning <code>nil</code>, so it does not try to send any method to <code>NilClass</code>, preventing a <code>NoMethodError</code>. As tadman points out in the comments, a catch-all exception handler is normally not a good idea. </p> <p><a href="https://github.com/rails/rails/blob/6ef9fda1a39f45e2d18aba4881f60a19589a2c77/activesupport/lib/active_support/core_ext/object/try.rb" rel="nofollow">https://github.com/rails/rails/blob/6ef9fda1a39f45e2d18aba4881f60a19589a2c77/activesupport/lib/active_support/core_ext/object/try.rb</a></p> <p><strong>Update</strong></p> <p>A better solution, and one that I forgot about, is to use <code>delegate</code>.</p> <p>For example:</p> <pre><code>class User &lt; ActiveRecord::Base delegate :contact, to: :survey, prefix: true, allow_nil: true end </code></pre> <p>Then you would call <code>user.survey_contact</code>, and would fail gracefully if the survey is <code>nil</code>.</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.
    1. VO
      singulars
      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