Check if record exists from controller in Rails

2019-01-10 02:30发布

In my app a User can create a Business. When they trigger the index action in my BusinessesController I want to check if a Business is related to the current_user.id:

  • If yes: display the business.
  • If no: redirect to the new action.

I was trying to use this:

if Business.where(:user_id => current_user.id) == nil
  # no business found
end

But it always returns true even when the business doesn't exist...

How can I test if a record exists in my database?

7条回答
我命由我不由天
2楼-- · 2019-01-10 03:05

I would do it this way if you needed an instance variable of the object to work with:

if @business = Business.where(:user_id => current_user.id).first
  #Do stuff
else
  #Do stuff
end
查看更多
登录 后发表回答