Sakkn
Sakkn

Reputation: 1

Change Controller to Not Error on Nil

I have a simple Show in my Users Controller. This just shows a list of that User's posts and comments. However if the user doesn't have any posts, I get an error:

Couldn't find post with 'id'=101. 

I understand the error, because there are no posts associated with that user, but how can I change my Users Controller to still function as it should (show posts and comments associated with a user) and not throw an error if posts = nil. For instance for a new user.

The issue isn't with my view, as I've completely deleted that and the error still throws. I originally tried to add an if user.posts? line, but the problem occurs before the view.

def show
    @user = User.find(params[:id])
    @posts = @user.posts.mostrecent.paginate(page: params[:page])
    @post = Post.find(params[:id])
    @comment = Comment.new
    @comments = @post.comments.paginate(page: params[:page])
end

I think I'm mudding up my controller, but this is the only way I got posts and comments to show correctly. Any help would be much appreciated.

Solution (kind of)

Added a Rescue to stop error from throwing if there are no posts:

    rescue ActiveRecord::RecordNotFound => e
    posts = nil

Upvotes: 0

Views: 30

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

this doesn't make sense in your controller

@user = User.find(params[:id])
...
@post = Post.find(params[:id])

The @user and @post would not have the same id except under some amazing coincidence. The @post would have a user_id that would match the user's id field.

If you want to retrieve a post that belongs to the user, you can do...

@post = Post.find_by(user_id: params[:id])

This will retrieve the first post it finds for the user, and it will return nil (without error) if no post exists.

Upvotes: 2

Related Questions