Rails 3.1 - 从视图中删除查询并在控制器或模型中处理它的正确方法
在视图中,我有以下内容:
<% @top_posts.each do |post| %>
<li>
<%= post.title %><br />
<%= link_to "Most popular comment", comment_path( post.comments.order("vote_cnt DESC").first )
</li>
<% end %>
我知道在视图中使用 post.comments.order("vote_cnt DESC").first
查询被认为是糟糕的形式。但是,由于我将帖子和评论数据组合起来创建单个列表项,因此我很难理解如何获取控制器中内置的数据“组合包”。我是否应该在控制器中构造某种@hash
,然后在视图中迭代@hash.each
?这是正确的做法吗?
或者是我的 Post 模型上的范围的工作?我是否缺少一些 ActiveRecord 魔法来使这变得简单?我在 RoR 上还是个新手,我才刚刚开始发现我有多少不明白的地方。
In a view I have the following:
<% @top_posts.each do |post| %>
<li>
<%= post.title %><br />
<%= link_to "Most popular comment", comment_path( post.comments.order("vote_cnt DESC").first )
</li>
<% end %>
I know it is considered poor form to have the post.comments.order("vote_cnt DESC").first
query in a view. However, since I'm combining both post and comment data to create a single list item, I'm having a hard time understanding how to get this "combo-pack" of data built in the controller. Should I be constructing some sort of @hash
in the controller and then iterate on @hash.each
in the view? Is that the right approach?
Or is the job for a scope on my Post model? Is there some ActiveRecord magic that I'm missing that makes this easy? I'm still pretty rookie at RoR, and am just beginning to see just how much I don't understand.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我要做的就是在我的
Post
模型中添加一个方法,以根据您的标准获取第一条评论。该视图将类似于comment_path(post.relevant_comment)
。What I'd do is add a method in my
Post
model to get the first comment according to your criterias. The view would then look likecomment_path(post.relevant_comment)
.