ruby-on-railsactiverecordhas-many-throughnomethoderror

Rails 3: include a field from has_many through association


My model association is as follows:

#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

So as noted above, A book has many similars through recommendations. My requirement is that while retrieving similars, I would also like to include the id of the corresponding record in the join table recommendations.
My questions are:


Solution

  • I recommend you read the Rails guide on associations, specifically about the has_many :through associations.

    A lot of your code doesn't make sense - for example:

    @book_similars = Book.similars
    

    This means you have a class method on the Book model for similars, but you don't mention it being defined, or what it returns. Rails just doesn't work like this.