Rails 3 查询接口:使用关联模型
我将使用通用博客示例。
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
当查询Post时,如何访问它的关联(即:comments)?
这应该是世界上最简单的事情,但我还没有找到任何关于它的文档。甚至http://edgeguides.rubyonrails.org/3_0_release_notes.html#query-interface 和 http://m.onkey.org/2010/1 /22/active-record-query-interface 毫无帮助,基本上是说“现在有像 joins 和 include 这样的方法可以做与 SQL 语句相同的事情。”是的,谢谢。
所以这里有一些我想做的非常简单的事情,虽然行不通,但应该是显而易见的我想要完成的事情:
Post.where(:comments.count >= 10)
Post.where(:comments.author_id == current_user.id)
Post.order(:comments.count)
我们如何才能做到这些而不诉诸带有 SQL 味道的 ruby 代码(从而违背了 Active Record 的目的) )? 谢谢 :)
I'll use the generic blog example.
class Post < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :post
end
When querying Post, how do you access its associations (i.e. :comments)?
This should be the easiest thing in the world, but I haven't found any documentation on it. Even http://edgeguides.rubyonrails.org/3_0_release_notes.html#query-interface and http://m.onkey.org/2010/1/22/active-record-query-interface were unhelpful, basically saying "Now there are methods like joins and includes to do the same thing as SQL statements." yeah thanks.
So here are very straightforward things I want to do, which do not work, but should be obvious what I'm trying to accomplish:
Post.where(:comments.count >= 10)
Post.where(:comments.author_id == current_user.id)
Post.order(:comments.count)
How can we do these without resorting to ruby code that reeks of SQL (thus defeating the purpose of Active Record)?
Thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你在Post上设置了counter_cache,你可以直接看到评论它有多少条评论而无需查询,这使得它变得更容易和更快。
这将解决您提出的第一个问题和最后一个问题。
然后您可以像这样查询它们,
但最好为此设置范围。
我不确定你想对第二个问题做什么,你想显示当前用户评论过的所有帖子吗?
If you set up a counter_cache on Post for the comments you can see directly how many comments it has without having to query, this makes it easier and faster.
This would take care of the first and last question you posed.
You can then query them like this,
But you are better off setting up scopes for that.
I'm not sure what you want to do with the second question, do you want to show all posts where the current user has commented on?
Post.where(:comments.count >= 10)
Post.where(:comments.author_id == current_user.id)
Post.order(:comments .count)
嘿,还有,我的两篇文章对 SQL 的描述有点重。我知道人们用 a 做得更优雅
,但我不知道该怎么说。对不起。
Post.where(:comments.count >= 10)
Post.where(:comments.author_id == current_user.id)
Post.order(:comments.count)
Hey also, my two posts are kinda heavy on the SQL. I know people do it more elgantly with a
But I'm not sure how to put that. Sorry.