Checking if ActiveRecord find returns a result

2020-06-01 04:54发布

I'm trying to check if a find method returns a result. My find method is the following:

post = Post.find(:all, :conditions => { :url => params['url'] }, :limit => 1)

What would be a good way to check that post contains a result?

7条回答
爷、活的狠高调
2楼-- · 2020-06-01 05:51

it may be as simple as changing your finder to:

post = Post.find(:first, :conditions => { :url => params['url'] })

With this finder, post will either return a single value or nil. Because nil behaves like false in a condition statement, you can say something like the following:

if post
  # do something
else
  # do something else
end
查看更多
登录 后发表回答