[英]Inherit and override Rails named scopes
是否有任何合理的方法來繼承命名范圍並在 Rails 中對其進行修改?
在我正在處理的應用程序中,有很多模型具有名為is_readable
的作用域。 這些模型中有許多是從少數基本模型繼承而來的。 其中一個子類需要為其is_readable
范圍添加一些限制,我想避免:
is_readable
檢查如果我理解你是對的(我可能不是),這應該有效:
因為作用域實際上只是類方法的語法糖,所以我們可以在其中使用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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.