向 ActiveRecord 添加范围会导致层次结构错误 [英] Adding scope to ActiveRecord causes hierarchy error

查看:33
本文介绍了向 ActiveRecord 添加范围会导致层次结构错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将所有 Rails 模型转换为使用 uuid 作为主键替换,但这破坏了 #first#last 方法,所以我试图添加一个默认范围,按 created_at 而不是 id 排序.

I've just converted all of my Rails models to use uuid as a primary key replacement, but this breaks the #first and #last methods so I'm trying to add a default scope that sorts by created_at instead of id.

我的担忧是这样的:

# config/initializers/uuid_support.rb
module 
  extend ActiveSupport::Concern

  included do
    default_scope -> { order 'created_at ASC' }
  end
end
ActiveRecord::Base.send :include, UuidSupport

添加此项后,在对任何模型执行提取时会引发以下错误:ActiveRecord::ActiveRecordError: ActiveRecord::Base 不属于从 ActiveRecord 向下的层次结构.

Once this has been added, the following error gets thrown when performing a fetch on any model: ActiveRecord::ActiveRecordError: ActiveRecord::Base doesn't belong in a hierarchy descending from ActiveRecord.

推荐答案

看起来您正在尝试创建一个关注点并让您的模型包含它.为此,我推荐一种不同的方法,而不是通过初始化程序来实现,而是作为一个实际问题,按照 Rails 的意图来实现.

Looks like you're trying to create a concern and have your models include it. For that, I recommend a different approach and not do it through an initializer, but rather as an actual concern, the way Rails intended it.

去掉你的初始化器,把下面的代码放到app/models/concerns/module_name.rb:

Get rid of your initializer, and put the following code in app/models/concerns/module_name.rb:

module ModuleName # replace with desired name
  extend ActiveSupport::Concern

  included do
    default_scope -> { order 'created_at ASC' }
  end
end

如果 <= Rails 3,将其添加到 application.rb 以加载关注点:

If <= Rails 3, add this to application.rb to load the concerns:

config.autoload_paths += %W(
  #{config.root}/app/models/concerns
)

通过做将您的关注纳入您的模型

Include your concern in your models by doing

include ModuleName

在模型的开头.

如果您使用初始化程序这样做的原因是因为您希望每个模型都包含此行为,那么现在是编写初始化程序的时候了.

If the reason you did this with an initializer is because you want every model to include this behavior, now is the time to write an initializer.

无论是猴子补丁:

# config/initializers/name.rb
class ActiveRecord::Base
  include ModuleName
end

或者像你一样:

# config/initializers/name.rb
ActiveRecord::Base.send :include, ModuleName

这篇关于向 ActiveRecord 添加范围会导致层次结构错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆