2014-11-11 2 views
0

나는 레일에서 세 개의 클래스가있는 경우 :Has_many 레일 협회 => NoMethodError

class Item::Part::Element < ActiveRecord::Base 
    belongs_to :item_part, :foreign_key => 'item_part_id' 
    self.table_name = 'item_part_elements' 
end 


class Item::Part < ActiveRecord::Base 
    has_many :elements 
    belongs_to :item, :foreign_key => 'item_id' 
    self.table_name = 'item_parts' 
end 

class Item < ActiveRecord::Base 
has_many :parts 
self.table_name = 'item' 
end 

와 나는

@item.parts 

가 잘 작동하지만 내가 전화를

@item_part.elements 
다음 한 경우를 호출하는 경우

은 오류를 throw합니다.

NoMethodError: undefined method "elements" 

연결이 잘못되었거나 다른 문제가 있습니까?

+1

모든 세부 사항을 모른 채 말하기는 어렵습니다. 인스턴스 변수를 어떻게 인스턴스화합니까? 또한'NoMethodError',하지만 무엇을 위해서? 'nil'을 위해서? – blelump

+0

NoMethodError : Item :: Part – bootsa

+0

에 대한 정의되지 않은 메서드 "elements"는 'item_part_id'및 'item_id'를 사용할 때'self'가 암시합니까? – pdoherty926

답변

1

이러한 연결에 클래스 이름을 지정해야한다고 생각합니다. 네임 스페이스가 없다면, 이것들은 잘 작동 할 것입니다. 그러나 단순히대신에 Item::Part::Element이 있으니 계속 진행하려면 ActiveRecord를 제공해야합니다. 이 시도 :

class Item::Part::Element < ActiveRecord::Base 
    belongs_to :item_part, :foreign_key => 'item_part_id' 
    self.table_name = 'item_part_elements' 
end 


class Item::Part < ActiveRecord::Base 
    has_many :elements, :class_name => '::Item::Part::Element' 
    belongs_to :item, :foreign_key => 'item_id' 
    self.table_name = 'item_parts' 
end 

class Item < ActiveRecord::Base 
has_many :parts, :class_name => '::Item::Part' 
self.table_name = 'item' 
end 

class_names로 시작하는 이유는 ":"당신이 네임 스페이스 구조의 최상위 (루트)에서의 네임 대신 현재의 모델을 기준으로하고 액티브을 알 수 있다는 것입니다.

솔직히 나는 @item.parts이 제대로 작동한다고 생각합니다.