Checking if ActiveRecord find returns a result

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

提交回复
热议问题