重新定义 default_scope 关注(in Rails)
Redefining default_scope in concern (in Rails)
我想在模型问题中重新定义 default_scope
,但我得到了这个:
You tried to define a scope named "default_scope" on the model "Product", but Active Record already defined a class method with the same name.
module SoftDeletable
extend ActiveSupport::Concern
included do
scope :default_scope, -> { where(deleted_at: nil) }
end
end
是的,我知道这有很多好处,但问题不在于此。
您知道如何设置 default_scope
关注吗?
谢谢
这个问题与将范围定义为问题的一部分并没有真正的关系。如果尝试从模型本身定义一个名为 default_scope
的范围,您会看到同样的错误。
要设置默认范围使用 default_scope
:
default_scope { where(deleted_at: nil) }
scope
用于创建您自己的命名范围,例如:
scope :non_deleted, -> { where(deleted_at: nil) }
会让你写
`Model.non_deleted.where....`
所以你问题中的代码试图创建一个名为 default_scope
的范围,但是错误消息表明范围 Model.default_scope...
将与现有的 default_scope
方法发生冲突用于设置默认范围。
我想在模型问题中重新定义 default_scope
,但我得到了这个:
You tried to define a scope named "default_scope" on the model "Product", but Active Record already defined a class method with the same name.
module SoftDeletable
extend ActiveSupport::Concern
included do
scope :default_scope, -> { where(deleted_at: nil) }
end
end
是的,我知道这有很多好处,但问题不在于此。
您知道如何设置 default_scope
关注吗?
谢谢
这个问题与将范围定义为问题的一部分并没有真正的关系。如果尝试从模型本身定义一个名为 default_scope
的范围,您会看到同样的错误。
要设置默认范围使用 default_scope
:
default_scope { where(deleted_at: nil) }
scope
用于创建您自己的命名范围,例如:
scope :non_deleted, -> { where(deleted_at: nil) }
会让你写
`Model.non_deleted.where....`
所以你问题中的代码试图创建一个名为 default_scope
的范围,但是错误消息表明范围 Model.default_scope...
将与现有的 default_scope
方法发生冲突用于设置默认范围。