【问题标题】:Rails 3: include a field from has_many through associationRails 3:通过关联包含来自 has_many 的字段
【发布时间】: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


【解决方案1】:

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

你的很多代码没有意义——例如:

@book_similars = Book.similars

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

【讨论】:

  • 我已经修改了问题以澄清关于 Book 模型上的类方法的事情。只需通过控制器中的 case 语句即可完成。为混乱道歉。对于手头的任务,我对 has_many :through 关联的理解相当清楚。然而,我的原始问题是找到一种 Rails 方法来包含关联表(推荐)的属性(Recommendation_ID)以及 has_many :through 返回的数据。注意推荐表的belongs_to,这就是.include(如前所述)不起作用的原因
猜你喜欢
  • 2017-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-27
  • 1970-01-01
  • 2012-05-30
相关资源
最近更新 更多