【问题标题】:Trying to set up default_scope but getting "Support for calling #default_scope without a block is removed" error尝试设置 default_scope 但出现“支持在没有块的情况下调用 #default_scope 已被删除”错误
【发布时间】:2016-07-25 01:32:55
【问题描述】:

我使用的是 Rails 4.2.3。我有这两个模型

class Address < ActiveRecord::Base
    …
    has_one :user

class User < ActiveRecord::Base
  belongs_to :address
  default_scope includes(:address) 

我想在加载“MyObject”时自动加载父关联,但在“default_scope”行出现此错误……

Support for calling #default_scope without a block is removed. For example instead of `default_scope where(color: 'red')`, please use `default_scope { where(color: 'red') }`. (Alternatively you can just redefine self.default_scope.)

如何调整我的“default_scope”行以自动加载我的父关联?

【问题讨论】:

    标签: ruby-on-rails-4 associations parent default-scope


    【解决方案1】:
    • 您的行中缺少块,更改如下:

      default_scope { includes(:address) }
      

    【讨论】:

    • 虽然将我的行更改为 "" 会导致错误消失,但当我调用 "User.find_by(id: session[:user_id])" 时,我的地址实体仍未加载。我已验证实际上存在与相关用户关联的地址 ID。
    • 我试过了,它对我有用。你如何用它验证地址的加载......例如您是否将结果作为 JSON 对象发送?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 2012-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多