【问题标题】:find(:first) and find(:all) are deprecated不推荐使用 find(:first) 和 find(:all)
【发布时间】:2013-02-26 20:48:37
【问题描述】:

我将RubyMine 与rails 3.2.12 一起使用,并且在我的IDE 中收到了已弃用的警告。任何想法如何解决这个已弃用的警告?

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

【问题讨论】:

    标签: ruby-on-rails-3 ruby-on-rails-3.1 ruby-on-rails-3.2


    【解决方案1】:

    @keithepley 发表评论后我改变了答案

    #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!
    

    罢工>

    您可以从this locations阅读更多内容

    不推荐使用的语句

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

    更好的版本

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

    最佳版本 (1)

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

    最佳版本 (2)

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

    【讨论】:

    【解决方案2】:

    这是 Rails 3-4 的做法:

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

      使用 Rails 3 中添加的新 ActiveRecord::Relation 内容。在此处查找更多信息:http://guides.rubyonrails.org/active_record_querying.html

      在您的模型上使用 #first、#last、#all 等,以及返回 ActiveRecord::Relation 的方法,例如 #where,而不是 #find。

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

      【讨论】:

      • User.where(:foo => true).all 和 User.all(:conditions => {:foo => true}) 有区别吗?
      • 至于返回值,否(在 Rails 2 和 3 中)。 Rails 4 将改为返回 ActiveRecord::Relation。但是条件哈希已被弃用
      猜你喜欢
      • 2022-01-21
      • 1970-01-01
      • 2018-08-26
      • 2014-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多