Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to create a conditional based on the existence of an attribute in Rails?
    primarykey
    data
    text
    <p>I have the following code in a likes_controller and it works fine as long as a <code>thing</code> has an <code>owner</code>. If not, it breaks. </p> <pre><code> def create @thing = Thing.find(params[:like][:liked_id]) user = @thing.owner current_user.like!(@thing) current_user.follow!(user) respond_with @thing end </code></pre> <p>I've tried using </p> <pre><code>user = @thing.owner if @thing.owner.exists? </code></pre> <p>but I get a NoMethodError:</p> <pre><code>NoMethodError in LikesController#create undefined method `exists?' for nil:NilClass </code></pre> <p>How do I check for the existence of an <code>owner</code>?</p> <p>I also now notice I'll have to put the second line (<code>current_user.follow!(user)</code>) in the block or it will break again...</p> <p>Edit: This worked (using @Amadan's answer):</p> <pre><code>def create @thing = Thing.find(params[:like][:liked_id]) current_user.like!(@thing) user = @thing.owner if user current_user.follow!(user) end respond_with @thing end </code></pre> <p>Additional information: In case anyone ever actually uses this, I should point out that one more small change is necessary to get this to work. The above code errors out if a <code>user</code> tried to <code>like</code> a <code>thing</code> when they are already <code>following</code> the <code>thing</code>'s <code>owner</code>. </p> <p>so instead of </p> <pre><code>if user </code></pre> <p>I used</p> <pre><code>if user &amp;&amp; !current_user.following?(user) </code></pre> <p>Hope this is helpful.</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