find(:first) and find(:all) are deprecated

ぃ、小莉子 提交于 2019-11-28 03:54:01

问题


I am using RubyMine with rails 3.2.12 and I am getting following deprecated warning in my IDE. Any Idea How can I solve this deprecated warning?

find(:first) and find(:all) are deprecated in favour of first and all methods. Support will be removed from rails 3.2.

回答1:


I changed my answer after @keithepley comment

#Post.find(:all, :conditions => { :approved => true })
Post.where(:approved => true).all

#Post.find(:first, :conditions => { :approved => true })
Post.where(:approved => true).first
or
post = Post.first  or post = Post.first!
or
post = Post.last   or post = Post.last!

You can read more from this locations

deprecated statement

Post.find(:all, :conditions => { :approved => true })

better version

Post.all(:conditions => { :approved => true })

best version (1)

named_scope :approved, :conditions => { :approved => true }
Post.approved.all

best version (2)

Post.scoped(:conditions => { :approved => true }).all




回答2:


Here is the Rails 3-4 way of doing it:

Post.where(approved: true) # All accepted posts
Post.find_by_approved(true) # The first accepted post
# Or Post.find_by(approved: true)
# Or Post.where(approved: true).first
Post.first
Post.last
Post.all



回答3:


Use the new ActiveRecord::Relation stuff that was added in Rails 3. Find more info here: http://guides.rubyonrails.org/active_record_querying.html

Instead of #find, use #first, #last, #all, etc. on your model, and the methods that return a ActiveRecord::Relation, like #where.

#User.find(:first)
User.first

#User.find(:all, :conditions => {:foo => true})
User.where(:foo => true).all


来源:https://stackoverflow.com/questions/15098961/findfirst-and-findall-are-deprecated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!