簡體   English   中英

Rails 3:從 has_many 到關聯包含一個字段

[英]Rails 3: include a field from has_many through association

我的模型關聯如下:

#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

所以如上所述,A book 通過推薦有很多相似之處 我的要求是,在檢索相似項時,我還想在連接表建議中包含相應記錄的id
我的問題是:

  • 我怎樣才能包括字段 *recommendation_id* 以及類似物

  • 如果不能直接包含,那么正確的方法是什么
    單獨確定這個字段(如上所示),然后將它注入到similars實例變量中,以便我可以直接在我的視圖中使用它?

我建議您閱讀有關關聯的 Rails 指南,特別是關於has_many :through associations

你的很多代碼沒有意義 - 例如:

@book_similars = Book.similars

這意味着您在Book模型上有一個類似的類方法,但您沒有提到它被定義,或者它返回什么。 Rails 不是這樣工作的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM