改进“:has_many :through”关联以检索数据
我正在使用 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 的做法” things":
@articles.category_relationships.where(:comment_id => @comment.id).map{ |category_relationship| category_relationship.article_category }
我应该怎么做?我可以\应该在 @articles.categories
关联上“工作”以改进上述代码吗?如果是这样,怎么办?
I am using Ruby on Rails 3.0.10 and I would like to improve some code (keep reading for more information) that retrieves data from the database using an :has_many :through
association.
In the model I have:
class Article < ActiveRecord::Base
has_many :category_relationships
has_many :categories,
:through => :category_relationships,
end
I would like to improve the following code (that retrieves article categories objects "filtering" some of those by using a where
statement) so to follow the "Ruby on Rails Way of doing things":
@articles.category_relationships.where(:comment_id => @comment.id).map{ |category_relationship| category_relationship.article_category }
How can\should I do that? Can\Should I "work" on the @articles.categories
association in order to improve the above code? If so, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你能使用像下面这样的东西吗?
如果您担心干燥,也许您可以将位置提取到模型中。
Can you use something like below?
If you are worrying about DRYness, maybe you could extract the where into the model.
我认为您需要在
Article
和CategoryRelationship
之间嵌套has_many :through
关系。这是一个我曾经成功使用过的插件,它可以准确地实现您所寻找的功能。https://github.com/ianwhite/nested_has_many_through
这篇博文还讨论了其他方法。
I think you need nested
has_many :through
relationship betweenArticle
andCategoryRelationship
. Here is a plugin that I had once used successfully to achieve exactly what you are looking for.https://github.com/ianwhite/nested_has_many_through
This blog post also discusses other approaches.