Checking if ActiveRecord find returns a result

后端 未结 7 1502
孤独总比滥情好
孤独总比滥情好 2021-02-07 08:03

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\'] },         


        
7条回答
  •  一生所求
    2021-02-07 08:23

    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
    

提交回复
热议问题