2011-09-23 2 views
1

이것은 내가 모든 LineItems를 얻을 인보이스 클래스의 기능을 가지고 싶습니다 has_many :through usage, simple, beginner questionhas_many : 통해 점점 관련된 항목

기본적으로이 질문에 대한 후속하지만 작동하지 않습니다 다음 :

너무 : 이전 질문에서 협회를 기반으로

> @i=Invoice.find(1)  # good 
> @i.products    # good works well 
> @i.products.line_items # not working, undefined method line_items 

이 작동해야 하는가? 제품에 직접 액세스해야한다고 생각합니다.

> @p=Product.find(1)  # good 
> @p.line_items   # also good 

이 모델을 기반으로 모든 광고 항목을 다시 가져 오는 방법은 무엇입니까?

들으

+0

가능한 중복 [has_many : 사용, 간단한, 초보자 질문을 통해 (http://stackoverflow.com/questions/7524528/has-many-through-usage-simple-beginner-question) –

+0

'has_many : through'는 ** ** 모든 ** 모델 객체가 아닌 ** 하나의 ** 모델 객체에서 간접적으로 액세스 할 수있는 모든 모델 객체를 가져올 수 있도록합니다. 아니, 작동하지 않아야합니다. – mliebelt

+0

귀하의 첫 번째 질문에 대한 내 대답을보십시오. 나는이 질문이이 점에 비추어 생각하지 않는다고 생각합니다. 일단 문제를 해결 한 후에는 다시 요청하십시오. [ "association methods"] (http://stackoverflow.com/questions/1529606/how-do-rails-association-methods-work)라는 것이 있습니다. 컬렉션 내에서 컬렉션을 선택하는 데 사용할 수 있습니다. –

답변

2

다음 한 모델 :

class Invoice 
    has_many :line_items 
    has_many :products, :through => :line_items 
end 

class LineItems 
    belongs_to :invoice 
    belongs_to :product 
end 

class Product 
    has_many :line_items 
    has_many :invoices, :through => :line_items 
end 

당신은 다음을 수행 할 수 있습니다 내가 @

= Invoice.find를 (1) # good
@ i.products # 잘 작동합니다.
@ i.line_items # 송장과 관련된 모든 line_items.

+0

은 LineItems를 Product와 Invoice 사이의 클래스로 만드는 것입니다. 필자가 모델을 만들려고 시도하는 것은 각 제품이 고유 한 'LineItem'이 내부 회계를위한 '비용'이라는 점에서 다소 괴로워합니다. 내가 본 ExAamples의 대부분은 두 개의 belongs_to가있는 클래스를 조인 클래스로 사용했기 때문에 묻습니다. 고마워 – timpone

1

@i.productsProduct의 컬렉션을 반환합니다. 당신은 모든 광고 항목을 수집해야합니다 당신을 가정

@i.products.collect(&:line_items) 
+0

@ i.products.sum ([], & : line_items) –

+0

배열 배열을 제공합니다. @ i.products.collect (& : line_items) .flatten' –

+0

또는 다음을 수행하는 것이 더 좋습니다 : @ i.products.sum ([], & : line_items) – rdvdijk

관련 문제