簡體   English   中英

繼承和覆蓋 Rails 命名范圍

[英]Inherit and override Rails named scopes

是否有任何合理的方法來繼承命名范圍並在 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM