2016-09-24 18 views
3

正如我理解的Ruby繼承和方法查找,當一個子實例調用父級的實例方法,而該方法又調用父和子都命名的方法,範圍仍然在子實例。所以會出現這種情況:ApplicationRecord關聯方法查找如何工作?

class Foo 

    def method1 
    "foo" 
    end 

    def method2 
    puts method1 
    end 
end 

class Bar < Foo 

    def method1 
    "bar" 
    end 
end 

Bar.new.method2 
=> "bar" 

然而,當我做我認爲是ActiveRecord關聯了類似的事情,我沒有得到我所期望的:

class Foo < ApplicationRecord 

    has_many :orders 
    has_many :order_items, through: :orders 
end 

class Bar < Foo 

    has_many :orders, -> { where(attribute1: 1) } 
end 

當我打電話bar.orders我得到了我的期望。但是當我打電話給bar.order_items時,我得到的結果與我調用foo.order_items時的結果相同(查詢範圍未使用)。如果我在bar.rb中包含has_many :orders_items, through: :orders,它的行爲如我所料。爲什麼ApplicationRecords的行爲方式如此?我是否將蘋果與橘子進行比較?

+1

我將蘋果與橘子比較? - 是的 - 第一個例子是實例方法的繼承,而'has_many:orders'是元類編程,它對類本身進行操作。 – max

回答

0

就像評論中的Max狀態一樣,當你使用元編程時,你並沒有定義方法,你正在調用它們,所以沒有涉及到繼承。