导轨控制器
Rails 新手
我有这个问题,我无法弄清楚。我已经按照 ruby 文档中的示例博客演示进行操作,但现在我遇到了问题。
假设在每个帖子的应用程序索引页面中,我还想显示该帖子的第一条评论。
当然,我需要循环所有帖子才能获取帖子 ID,但如何才能获得该帖子的第一条评论?
我如何管理 homeController 和视图?
从现在开始谢谢!
Newb in Rails
i Have this problem that i cannot figure out. I've followed the sample blog dimostration form the ruby doc but now i have a problem.
Let's say that in the app index page for each post i also want to show the first comment of that post.
sure i need to cycle all the post to get the post id but how can i get the first comment of that post?
how can i manage the homeController and the view ?
thanks since now!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
遵循您提出的问题有点困难,详细的语法可能会有所不同,但您会想要类似的东西
(find_by_x 根据您的顺序默认为 x 的第一个,所以这只会返回一个元素。
我希望有帮助。
It's a bit hard to follow the question you're asking and the detailed syntax might vary, but you're going to want something like
(find_by_x defaults to the first of x based on your ordering, so this will only return one element.
I hope that helps.
更好的方法是:
@post.comments.first
。并在找到您的帖子时立即加载您的评论:
@posts = Post.all(:include => :comments)
这样,每个请求只需运行一个查询。在前面的答案中,您为索引页面上的每个帖子运行一个附加的 select 语句。
a better approach would be:
@post.comments.first
.and eager load your comments when you find your posts:
@posts = Post.all(:include => :comments)
This way, you only run one query per request. In the previous answer you run an additional select statement for every post on the index page.