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:31

You can try ActiveRecord::Base.exists? before

Post.exists?(:conditions => { :url => params['url'] })
查看更多
Viruses.
3楼-- · 2020-06-01 05:32

Another way to do it is checking with ActiveRecord#any?.

查看更多
疯言疯语
4楼-- · 2020-06-01 05:33

if post doesn't contain any result it will be an empty list and then:

post.empty?

will return true.

查看更多
啃猪蹄的小仙女
5楼-- · 2020-06-01 05:38

Use the BANG! version of the find_by_url method to get it to raise an exception of it could not be found and then rescue it later on in that same method/action.

def show
  Post.find_by_url!(params[:url])
  rescue ActiveRecord::RecordNotFound
    flash[:notice] = "The URL you were looking for could not be found."
    redirect_to root_path
  end
end

If you didn't raise an exception here I believe that Rails would show the public/404.html page.

查看更多
做个烂人
6楼-- · 2020-06-01 05:43

find :all returns an empty array ([]) if no rows are returned, so you can just use it this way:

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

unless post.empty?
  # do something...
end

By the way, if you do find :all you're going to get an array, not a single row. If you're trying to get just one Post, it would be cleaner to use the find_by helper or find :first or just first instead:

post = Post.find_by_url params['url']

# or

post = Post.first :conditions => { :url => params['url'] }

# then...

if post
  # do something...
end
查看更多
等我变得足够好
7楼-- · 2020-06-01 05:49
Post.find_by_id(id_column_value)

will return nil rathering than blowing up your program when it can't find a record.

Of course, there's

x = Post.where(:any_column_name => value) 

which always returns an array of results. In which case you could just run an

x.each {|t| f(t) }

or

y = x.map {|t| f(t)}

or of course,

x[0], x[1], etc

Sorry I got a little carried away there

查看更多
登录 后发表回答