2
다음과 같이

내 모델 협회는 다음과 같습니다 위에서 언급 한 바와 같이 레일 3 : 협회를 통해 has_many에서 필드를 포함

#book model 
class Book < ActiveRecord::Base 
has_many :recommendations, :dependent => :destroy 
has_many :similars, :through => :recommendations, :conditions => ['recommendation_type IS NULL'], :order => 'recommendations.created_at DESC' 

#recommendation model 
class Recommendation < ActiveRecord::Base 
belongs_to :book 
belongs_to :similar, :class_name => 'Book', :foreign_key => 'similar_id' 

#Books_controller - injecting the recommendation_id 
@book = Book.find(params[:id]) 
if params[:content_type] 
    @content_type = params[:content_type]; 
else 
    @content_type = "similars" 
end 

case @content_type 

when "similars" 
    # get the similars 
    @book_content = @book.similars 
    @book_content.each do |similar| 
    @rec_id = Recommendation.where(:book_id=>similar.id, :recommendation_type=>'S').select('id').first.id 
    similar << {:rec_id => @rec_id} 
    # ^-- Above line gives NoMethodError (undefined method `<<' for #<Book:0x10de1f40>): 
    end  

when "references" 
    # get the references 
    @book_content = @book.references 
    @book_content.each do |reference| 
    @rec_id = Recommendation.where(:book_id=>reference.id, :recommendation_type=>'R').select('id').first.id 
    reference << {:rec_id => @rec_id} 
    # ^-- Above line gives NoMethodError (undefined method `<<' for #<Book:0x10de1f40>): 
    end 
end 

그래서, 책은 Similars 참조 을 통해 권고 많은있다. 내 요구 사항은 similars을 검색하는 동안 id (권장 검색어는)의 해당 레코드가 포함되어 있습니다.
내 질문은 :

  • 어떻게 Similars 참조 alongwith 필드 *의 recommendation_id *을 포함 할 수있다?

  • 가 직접 포함시킬 수없는 경우
    하는 올바른 방법이 위와 같이 개별적으로이 필드를 결정하고 I가 직접 사용할 수 있도록 Similars 참조로 인스턴스 변수를 주입 무엇 내 견해로?

+1

여기에서 수행하려는 작업은 권장 사항에 따라 similars를 적용 하시겠습니까? 좀 더 자세한 내용을 추가하면 더 나은 응답을 얻을 수 있습니다. –

+0

@MatthewLehner, 의견 주셔서 감사합니다. 나는 게시물을 편집하여 자세한 내용을 포함 시켰습니다. 친절하게 도와주세요. – rgoraya

+0

@ similar.recommendation_id를 사용할 수 없습니까? - 그래도 작동하지 않는다면 비슷한 모델과 뷰 논리를 게시하십시오. –

답변

0

관련 정보에 대한 레일스 가이드를 특히 has_many :through associations에 게시하는 것이 좋습니다.

@book_similars = Book.similars 

이것은 당신이 Similars 참조에 대한 Book 모델 클래스 메소드를 의미하지만, 당신은 정의되는 언급하지 않는, 또는 예를 들어 -

코드의 많은 이해가되지 않습니다 그것은 무엇을 반환합니다. 레일스는 이와 같이 작동하지 않습니다.

+0

Book 모델의 클래스 메소드에 대한 문제를 명확히하기 위해이 질문을 수정했습니다. 그것은 단순히 컨트롤러의 case 문을 통해 수행됩니다. 혼란에 사과드립니다. 내가 가진 has_many : association에 대한 나의 이해는 당면 과제에 대해 상당히 명확하다. 그러나 내 * 원래 질문 *은 has_many : through가 반환 한 데이터와 함께 연관 테이블 (권장 사항)의 속성 (Recommendation_ID)을 포함하는 Rails 방법을 찾는 것입니다. .include (앞에서 제안한대로)가 작동하지 않는 이유 인 추천 테이블의 belongs_to에 유의하십시오. – rgoraya

관련 문제