【问题标题】:Rails scope when upgrading from 3 to 4从 3 升级到 4 时的 Rails 范围
【发布时间】:2014-07-14 22:50:15
【问题描述】:

从 Rails 3 升级到 Rail 4 时,我收到“ActiveRecord 关联中范围块和已弃用的查找器选项的无效组合”错误。关于这个问题有几篇文章,其中一些使用的格式如下:

has_many :readable_exams,
         -> { where trashed_at: nil },
         through: :student

但是,当我使用这种格式时,我收到了无效错误。另一方面,当我这样做时:

has_many :readable_exams,
         -> { where(trashed_at: nil)
              .through(:student) }

没有错误被抛出。谁能解释为什么 through 在第一种情况下会引发错误,而不是在第二种情况下?

编辑: 事实证明,我的错误来自一个包装了我之前忽略的 has_many 的 with_options 块。

with_options source: :exams,
             primary_key: "student_id",
             group: "exams.id" do |user| # This was throwing the error
    user.has_many :readable_exams,
                  -> { where trashed_at: nil },
                  through: :student
    ...

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-4 scope


    【解决方案1】:

    through 选项不是在作用域块中调用的函数。你需要说:

    has_many :exams, -> { where(trashed_at: nil) }, through: :student

    关联现在采用可选的第二个参数,一个块,它可以为关联指定某些约束(因此是范围块)。您可以在以下指南中找到哪些方法有效:http://guides.rubyonrails.org/association_basics.html 第 4.3.3 节介绍了 has_many 关联的有效方法。

    要记住的一点是,在作用域块中调用的所有方法都是ActiveRecord 查询接口的一部分,之后的所有内容都是关联的选项。

    【讨论】:

    • 感谢您告诉我为什么第二个没有抛出错误!不过,我仍然很困惑为什么第一种格式(与您的相同)给我一个错误。当我通过:删除时,错误消失了。有什么想法吗?
    猜你喜欢
    • 1970-01-01
    • 2019-06-18
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多