Question

When calling all posts for a user Posts.find(creator: current_user:_id), and the user hasn't made any...rails spits a "NoMethodError" for it...

What I want to do is have a pretty output for the user of "Why, no. You haven't posted anything, you lazy slob." instead of this scary error.

What's the best way to handle things like this?

Was it helpful?

Solution

You need to use where instead of find. By design, find method expect to actually find an existing thing you're looking for. Consult docs about querying here.

Also, you can try and use try method. Basically it's equal to the following:

object.try(:something_scary)
# is equal to
object && object.something_scary

This is how I handle nil entities. If you want to show some kind of message to user (about being slobby) you make a check inside of your template and render different partials. Example:

   <% if @posts.present? %>
     <%= render 'posts' %>
   <% else %>
     <%= render 'no_posts' %>
   <% end %>

Then you can put your message inside of that no_posts partial.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top