2

我的模型关联如下:

#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实例变量中以便我可以在视图中直接使用它的正确方法是什么?

4

1 回答 1

0

我建议您阅读有关关联的 Rails 指南,特别是有关has_many :through associations的内容。

您的很多代码没有意义 - 例如:

@book_similars = Book.similars

这意味着您在Book模型上有一个类似的类方法,但您没有提到它被定义,或者它返回什么。Rails 不能这样工作。

于 2012-01-31T17:44:11.030 回答