Note that there are some explanatory texts on larger screens.

plurals
  1. PORails 3: include a field from has_many through association
    text
    copied!<p>My model association is as follows:</p> <pre><code>#book model class Book &lt; ActiveRecord::Base has_many :recommendations, :dependent =&gt; :destroy has_many :similars, :through =&gt; :recommendations, :conditions =&gt; ['recommendation_type IS NULL'], :order =&gt; 'recommendations.created_at DESC' #recommendation model class Recommendation &lt; ActiveRecord::Base belongs_to :book belongs_to :similar, :class_name =&gt; 'Book', :foreign_key =&gt; '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=&gt;similar.id, :recommendation_type=&gt;'S').select('id').first.id similar &lt;&lt; {:rec_id =&gt; @rec_id} # ^-- Above line gives NoMethodError (undefined method `&lt;&lt;' for #&lt;Book:0x10de1f40&gt;): end when "references" # get the references @book_content = @book.references @book_content.each do |reference| @rec_id = Recommendation.where(:book_id=&gt;reference.id, :recommendation_type=&gt;'R').select('id').first.id reference &lt;&lt; {:rec_id =&gt; @rec_id} # ^-- Above line gives NoMethodError (undefined method `&lt;&lt;' for #&lt;Book:0x10de1f40&gt;): end end </code></pre> <p>So as noted above, A book has many <em>similars</em> through <em>recommendations</em>. My requirement is that while retrieving <em>similars</em>, I would also like to <strong>include the <em>id</em> of the corresponding record in the join table <em>recommendations</em>.</strong><br> My questions are:</p> <ul> <li><p>How can I include the field *recommendation_id* alongwith <em>similars</em>?</p></li> <li><p>If it cannot be included directly, then what is the correct way to<br> determine this field separately (as shown above) and then inject it into the <em>similars</em> instance variable so that I can use it directly in my views?</p></li> </ul>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload