Denny Denny - 6 months ago 18
Ruby Question

Is an expression interpreted differently in irb and rails?

I have just noticed

User.where("id = '309'")

works in IRB console. However it doesn't work in my controller. I wonder why?

In contrast, User.find(309) works in both irb console and my controller.

In my controller,

before_action :correct_user, only: [:edit, :update],

private
def correct_user
@user = User.where("id = '309'")
redirect_to(root_url) unless current_user?(@user)
end
end


This does not work. The view webpage does not open with no error message.

If User.find(309) instead. It will work by going to correct view webpage.

Answer

Seems like you may be expecting the same behavior from User.find and User.where. User.find will automatically grab an actual User, whereas User.where will grab a search query that sort of functions as an array. Try putting .last after the where. Like this:

@user = User.where("id = '309'").last