在 Rails 中渲染不同类的集合

发布于 2024-07-29 16:43:40 字数 258 浏览 5 评论 0原文

我有一个包含几个不同类的实例的集合,我想渲染每个实例的部分。 我可以使用以下代码来执行此操作:

<%= render @results %>

我的问题是:如何在不同的基目录中呈现不同的部分? 上面的代码将查找 app/views/stories/_story.html.erb,但是,此操作的部分内容都保存在不同的目录中 - app/search/_story.html.erb。 有什么方法可以指定这一点吗?

I have a collection that contains instances of several different classes, and I want to render the partial for each instance. I can do this using the following code:

<%= render @results %>

My question is: How can I render the different partials in a different base directory? The above code will look for app/views/stories/_story.html.erb, however, the partials for this action are all kept in a different directory - app/search/_story.html.erb. Is there any way of specifying this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

好久不见√ 2024-08-05 16:43:41

或者你可以使用 is_a?(Object)

if is_a?(classA)
 render something_A
elsif is_a?(classB)
  render something_B
end

or you can use is_a?(Object)

if is_a?(classA)
 render something_A
elsif is_a?(classB)
  render something_B
end
分分钟 2024-08-05 16:43:41

我有一个类似的情况,我有多个类,所以我对每个类使用一个部分,例如:

for result in @results
  = render :partial => "result_#{result.class.to_s.downcase}", :locals => {:item => result}
end

I have a similar situation where I have multiple classes so I use a partial for each class like:

for result in @results
  = render :partial => "result_#{result.class.to_s.downcase}", :locals => {:item => result}
end
最偏执的依靠 2024-08-05 16:43:40

您可以创建一个像这样的辅助方法:

def render_results(results)
  result_templates = {"ClassA" => "search/story", "ClassB" => "something/else"}
  results.each do |result|
    if template = result_templates[result.class.name]
      concat render(:partial => template, :object => result)
    end
  end
end

然后在视图中调用 <% render_results(@results) %>

You could create a helper method like this:

def render_results(results)
  result_templates = {"ClassA" => "search/story", "ClassB" => "something/else"}
  results.each do |result|
    if template = result_templates[result.class.name]
      concat render(:partial => template, :object => result)
    end
  end
end

And then in the view call <% render_results(@results) %>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文