2013-06-10 1 views
1

내가 않는 이유는 모델의 몇has_and_belongs_to_many가 인스턴스 메소드가 아닌 클래스 메소드를 추가하는 이유는 무엇입니까? 이 추가되어야하는 동안

class Product < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
end 

지금

class Category < ActiveRecord::Base 
    has_and_belongs_to_many :products 
end 

왜 내가

prod = Product.new 
prod.categories << Category.new 

을 말할 수있다 has_and_belongs_to_manyProduct#categories<< 같은 클래스 메소드를 추가 인스턴스 메서드?

어떻게 이러한 클래스 메서드를 사용하여 연결을 설정할 수 있습니까?

+0

. 왜 그렇지 않다고 생각하니? 당신은 예를 협회로 액세스 할 때이 http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many – michelpm

+0

는 오류 메시지를 받고 있습니까? 번호 – nik7

+0

에 따라 – lurker

답변

2

, 즉 당신은 아마 누락 것입니다 :

인스턴스 방법이다
prod = Product.new    # This is a Product instance 
prod.categories << Category.new # This works 

prod = Product.where(name:'x') # This returns a query (ActiveRecord::Relation) 
prod.categories << Category.new # This doesn't work 

prod = Product.where(name:'x').first # This is a Product instance 
prod.categories << Category.new  # This works 
0

새로운 객체를 생성 할 때 (의이 Product을 가정 해 봅시다), 당신은 그 연결을 작성하고 저장 호출 할 .build 방법을 사용할 수 있습니다!

편집 : 여기에 당신이 내게 준 오류 코드와 좋은 read

+0

제품의 모든 인스턴스는 카테고리에 대한 액세스 권한이 있어야 인스턴스 메소드가되어야한다는 것을 의미하지만 실제로는 클래스 메소드입니다. 질문을 다시 읽으십시오. – nik7

+0

위의 편집을 참조하십시오. – kushyar

관련 문제