2

我是 Ruby on Rails 新手,对关联对象的视图逻辑有疑问:

我的模型看起来类似于

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
end

我想要显示的是所有帖子的列表以及每个帖子的前三个评论。

所以,我保持后控制器索引操作简单

class PostController < ApplicationController
  #..
  def index 
    @posts = Post.find(:all)
  end
  #..
end

现在在views/posts/index.html.erb我可以做这样的事情@posts.comments ,我可以循环前三个条目。但是我如何访问通常在模型中完成的功能(在这种情况下是关联的模型),例如视图(或控制器)中的排序、范围等?

4

2 回答 2

1

您应该避免在视图中编写复杂的业务登录。在这种情况下,您的执行非常简单,您可以在视图中编写所有代码。它应该看起来像这样

<% @posts.each do |post| %>
  <% @post.comments.all(:limit => 3, :order => "created_at DESC").each do |comment| %>
      do something
  <% end %>
<% end %>

有几个可能的改进。首先,使用 named_scope。

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to  :post
  named_scope :recent, proc { |limit| :limit => limit || 3, :order => "created_at DESC") }
  # you can also hard-code the limit value (ScottD)
  named_scope :recent, :limit => 3, :order => "created_at DESC"
end


<% @posts.each do |post| %>
  <% @post.comments.recent.each do |comment| %>
      do something
  <% end %>
<% end %>

如果我是对的,可以删除 .each 。

<% @posts.each do |post| %>
  <% @post.comments.recent do |comment| %>
      do something
  <% end %>
<% end %>

如果您愿意,您还可以定义自定义关系(这适用于非常复杂的关系)。

于 2009-06-22T19:04:00.297 回答
1

您可以在指定限制的关联上使用 find 方法,例如:

@post.comments.find(:all, :limit => 3)

在您看来,或者您可以在 Post 模型中创建另一个关联,例如:

has_many :first_three_comments, :limit => 3, :class_name => "Comment" 

然后你可以参考那个关联,比如

@post.first_three_comments.each 做 |comment| ...

希望有帮助。

于 2009-06-22T19:05:54.927 回答