2012-09-17 3 views
0

상자에서 모든 항목에 대한 데이터를 검색하려고하는데 상자에 구획이있을 수 있으며 모든 구획 정보를 상자 수준에서 가져오고 싶습니다. 상자는 반드시 구획을 가질 필요가 없기 때문에 항목은 다형성을 갖습니다.레일 : 중첩 모델의 다형성 데이터 검색

모델

내가 함께 결과를 다시 얻을 수 있습니다 내 컨트롤러에서
class Box < ActiveRecord::Base 
    has_many :compartments 
    has_many :items, :as => :itemable 
end 

:

@box = Box.find(params[:id]) 

@itemable = @box.compartments.first 

@itemable = @box.compartments.last 

VIEW

<% @items.each do |item| %> 
<%= item.name %> 
<% end %> 

하지만 다음 시도하는 경우

@itemable = @box.compartments 

또는

@itemable = @box.compartments.find(:all) 

나는

undefined method `items' for #<ActiveRecord::Array> 

또는

undefined method `items' for #<ActiveRecord::Relation> 

사람이 모든 구획에서 다시 결과를 얻는 도와 드릴 오류를 얻을?

+0

': as => : itemable'에 따라'.itemables'를 사용해야합니까? – pdoherty926

+0

Itemable 클래스와 Compartment 클래스에서 'belongs_to'를 정의 했습니까? – megas

+0

@megas 항목은 다형성이므로 Compartment에서 has_many : items, : as : 항목이 너무 있음 – ritchielee

답변

0

그래서 구획에 당신이

belongs_to :box 
has_many :items, :as => :itemable 

는이 경우 있나요? @box.compartments 구획 배열을 반환해야합니까? items이 어쨌든 @box.compartments을 호출하는 것 같습니다.

+0

예, 컴 파트먼트는 belongs_to 상자입니다. @ box.compartments가 [@items = @ itemable.first.items] 할 수있는 후 # ritchielee

+0

에 대한 정의되지 않은 메소드'items '에 대한 @ box.compartments의 변경 사항을 알았습니다. 배열이 작동하는 것처럼 보입니다 - 컨트롤러에서 이것을 루프하는 방법을 알아 내야합니다. – ritchielee

+0

'@itemable = @ box.compartments'가 오류를 던져서'@ itemable.first.items'을 시도 할 수 없었을 것이라고 생각했습니다. – Ramfjord