ruby-on-rails - 在 Rails 中使用相同部分时显示不同数据的最佳实践

标签 ruby-on-rails scopes

只是一个与 Rails 最佳实践相关的问题:

假设我们有一个帖子和评论模型。相同的部分用于在索引 View 和显示 View 上呈现帖子。该部分内部是对呈现注释的另一个部分的引用。

post_controller.rb

def index
  @posts = Post.all
end

def show
  @post = Post.find(params[:id])
end

_post.html.haml

.post
  = post.content 
  = render 'comments/list', :comments => post.comments

评论/_list.html.haml

- comments.each do |c|
    c.comment

现在假设对于帖子索引 View ,我们只想显示每个帖子的最后 3 条评论,但在显示 View 上我们想要显示该帖子的所有评论。因为使用了相同的部分,所以我们无法编辑调用来限制评论。实现这一目标的最佳方法是什么?目前我已将其抽象为一个助手,但感觉有点狡猾:

def limited_comments(comments)
  if params[:controller] == 'posts' and params[:action] == 'show'
    comments
  else
    comments.limit(3)
  end
end

这意味着 _post.html.haml 更改为读取

= render 'comments/list', :comments => limited_comments(post.comments)

它可以工作,但感觉不像 Rails 的方式。我猜有一种使用范围的方法,但我似乎无法弄清楚。

最佳答案

我相信@benchwarmer想说的是最好将参数传递给_post部分。直接的 @comments 不起作用,但类似下面的代码可能会:

def index
  @posts = Post.all
  render :partial => @posts, :locals => { :max_comments => 3 }
end

def show
  @post = Post.find(params[:id])
  render :partial => @post, :locals => { :max_comments => false }
end

在 post.html.haml 中:

= render 'comments/list', :comments => limited_comments(post.comments,max_comments)

你的 helper :

def limited_comments(comments,max_comments)
  max_comments ? comments.limit(max_comments) : comments
end

我没有编译,所以你可能需要进一步处理传递给 render :partial 的参数(在这种情况下,你可能必须单独设置 :partial 和 :object/:collection ,或者其他的) ,我不记得了,也没有尝试过)。但我希望,这个想法是明确的 - 将逻辑表示(所有注释或最后 3 个)与处理路径(哪个 Controller /操作)分开。也许您稍后会想要显示嵌入在另一个列表中的评论的帖子(用户列表的最后 3 个帖子),那么这种分离就会派上用场。

如果您不想在 Controller 级别公开所有内部逻辑细节,您也可以执行以下操作:

def index
  @posts = Post.all
  render :partial => @posts, :locals => { :comments_list_type => :short }
end

def show
  @post = Post.find(params[:id])
  render :partial => @post, :locals => { :comments_list_type => :full }
end

然后,在 post.html.haml 中:

= render 'comments/list', :comments => build_comments_list(post.comments,comments_list_type)

你的 helper :

def limited_comments(comments,comments_list_type)
  case comments_list_type
    when :short
      comments.limit(3) 
    when :long
      comments.limit(10) 
    when :full
      comments
  end
end

关于ruby-on-rails - 在 Rails 中使用相同部分时显示不同数据的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15117090/

相关文章:

ruby-on-rails - Rails ActiveRecord has_many 通过不工作

ruby-on-rails - 在 ruby​​ 中遍历 CSV

ruby-on-rails - 使用 Rails/Devise 处理多个范围/角色登录和注销的最佳方法是什么?

ruby-on-rails - 在 Rails 中添加模型范围的文档

google-sheets-api - 使用应用程序默认凭据访问 Google Sheet API

ruby-on-rails - Rails 3 - 没有型号名称的家庭住址?

ruby-on-rails - link_to 在 rails 中发布编辑 View

javascript - 在 JavaScript 中模拟 Rails 表单提交

Django-Allauth 范围不适用于任何提供程序

ruby-on-rails - 如何在Rails 4中将参数传递给has_many关联范围?