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"
, 내가 기대하는 것을 얻을하지 않습니다
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
(쿼리 범위가 사용되지 않음)을 호출 한 것과 같은 결과가 나타납니다. has_many :orders_items, through: :orders
을 bar.rb에 포함하면 예상대로 작동합니다. 왜 ApplicationRecords는 이런 식으로 행동합니까? 사과와 오렌지를 비교합니까?
사과를 오렌지와 비교합니까? - 예 - 첫 번째 예는 인스턴스 메소드의 상속이며, 반면에 'has_many : orders'는 클래스 자체에서 작동하는 메타 프로그래밍입니다. – max