我正在使用Ruby on Rails 3.0.10,我希望改进一些代码(继续阅读以获取更多信息),这些代码使用:has_many :through
关联从数据库中检索数据。
在模型中我有:
class Article < ActiveRecord::Base
has_many :category_relationships
has_many :categories,
:through => :category_relationships,
end
我想改进以下代码(通过使用where
语句检索文章类别对象“过滤”其中一些),以便遵循“Ruby on Rails做事方式”:
@articles.category_relationships.where(:comment_id => @comment.id).map{ |category_relationship| category_relationship.article_category }
我该怎么做?可以\我应该在@articles.categories
关联上“工作”以改进上述代码吗?如果是这样,怎么样?
答案 0 :(得分:0)
我认为您需要has_many :through
和Article
之间的嵌套CategoryRelationship
关系。这是一个插件,我曾经成功地用来实现你正在寻找的东西。
https://github.com/ianwhite/nested_has_many_through
This博客文章还讨论了其他方法。
答案 1 :(得分:0)
你能用下面的东西吗?
@articles.categories.where(["category_relationships.comment_id = ?",
@comment.id])
如果您担心干燥,也许您可以提取模型中的位置。
class Article < ActiveRecord::Base
has_many :category_relationships
has_many :categories,
:through => :category_relationships do
def has_comment(comment_id)
where(["category_relationships.comment_id = ?", comment_id])
end
end
end
@articles.categories.has_comment(@comment.id)