Checking if ActiveRecord find returns a result

后端 未结 7 1509
孤独总比滥情好
孤独总比滥情好 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:18
    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

    0 讨论(0)
  • 2021-02-07 08:21

    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.

    0 讨论(0)
  • 2021-02-07 08:22

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

    post.empty?
    

    will return true.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-02-07 08:28

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

    0 讨论(0)
  • 2021-02-07 08:29

    You can try ActiveRecord::Base.exists? before

    Post.exists?(:conditions => { :url => params['url'] })
    
    0 讨论(0)
提交回复
热议问题