【发布时间】:2012-01-29 21:56:03
【问题描述】:
我的模型关联如下:
#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
如上所述,一本书通过推荐有许多相似之处。我的要求是,在检索相似项的同时,我还想在连接表recommendations中包含相应记录的id。
我的问题是:
如何将 *recommendation_id* 字段与 相似?
如果不能直接包含,那么正确的方法是什么
分别确定这个字段(如上图),然后 将其注入到 similars 实例变量中,以便我可以使用 直接在我看来?
【问题讨论】:
-
您在此处尝试通过推荐范围相似的内容做什么?添加更多细节,您会得到更好的响应。
-
@MatthewLehner,感谢您的评论。我编辑了帖子以包含更多细节。请帮忙。
-
你不能只使用@similar.recommendation_id 吗? - 如果这不起作用,请发布您的相似模型和您想到的视图逻辑。
-
另外,
NoMethodError是因为您将Similar对象视为散列或数组。您不能即时为对象添加属性。 -
@MatthewLehner,相似物不是模型!它是:通过推荐模型。
标签: ruby-on-rails activerecord has-many-through nomethoderror