继承并覆盖Rails命名的作用域



有什么合理的方法可以继承命名作用域并在Rails中修改它吗?

在我工作的应用程序中,有很多模型的作用域为is_readable。这些模型中的许多都继承自少数几个基本模型。其中一个子类需要向其is_readable范围添加一些限制,我希望避免:

  1. 给子类的作用域一个新名称,因为这样标准的is_readable检查就不能通用地执行
  2. 复制粘贴超类的作用域定义到子类中,因为以后对超类作用域的任何更改都不会出现在子类中

如果我对你的理解是正确的(我可能不是(,这应该是有效的:

因为作用域实际上只是类方法的语法糖,所以我们可以在其中使用super

ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.boolean :readable
end
create_table :comments, force: true do |t|
t.boolean :readable 
t.boolean :active
end
end
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true 
scope :is_readable, -> { where(readable: true) }
end
class Post < ApplicationRecord
end
class Comment < ApplicationRecord
def self.is_readable
super.where(active: true)
end
end
class IsReadableTest < Minitest::Test
def test_scope
5.times { Post.create!(readable: true) }
3.times { Comment.create!(readable: false, active: false) }
2.times { Comment.create!(readable: true, active: true) }
assert_equal 5, Post.count
assert_equal 5, Post.is_readable.count
assert_equal 5, Comment.count
assert_equal 2, Comment.is_readable.count 
end
end

最新更新