2

経由にhas_manyからフィールドを含める私のモデルの関連付けがある:上記のようにRailsの3:次のように関連

#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を伴って含むフィールド*のrecommendation_id *を含めることができますか?

  • が直接含めることができない場合、何が(上記のように)
    への正しい道を別々にこのフィールドを決定し、次いで I直接 それを使用できるようにsimilarsインスタンス変数に注入私の見解では?

+1

ここで何をしようとしていますか?いくつかの詳細を追加すれば、より良いレスポンスが得られます。 –

+0

@MatthewLehner、コメントありがとう。私はポストを編集して詳細を掲載しました。親切に助けてください。 – rgoraya

+0

@ similar.recommendation_idは使えませんか? - それがうまくいかない場合は、似たようなモデルとあなたが覚えているビューロジックを投稿してください。 –

答えて

0

特に、has_many :through associationsについては、関連に関するRailsガイドを読むことをお勧めします。

あなたのコードの多くは意味がありません - 例えば:

@book_similars = Book.similars 

は、これはあなたがsimilarsためBookモデルにクラスメソッドを持っていますが、あなたはそれが定義されて言及していない、または意味しますそれは何を返します。 Railsはこのように動作しません。

+0

Bookモデルのclassメソッドに関することを明確にするために質問を修正しました。コントローラーのcaseステートメントを通して簡単に実行されます。混乱の謝罪has_many:through associationの私の理解は、手近な課題に対してかなり明確です。しかし、私の元の質問*は、has_many:throughによって返されたデータとともに、関連テーブル(推奨)の属性(Recommendation_ID)を含めるためのRailsの方法を見つけることです。 .include(前述のように)が動作しない理由である推奨テーブルのbelongs_toに注意してください – rgoraya

関連する問題