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:
-
How can I include the field *recommendation_id* alongwith
similars? -
If it cannot be included directly, then what is the correct way to
determine this field separately (as shown above) and then
inject it into the similars instance variable so that I can use
it directly in my views?
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:
This means you have a class method on the
Bookmodel for similars, but you don’t mention it being defined, or what it returns. Rails just doesn’t work like this.