如何使用渲染部分传递选项

时间:2015-04-26 22:06:21

标签: ruby-on-rails ruby

有没有办法传递渲染部分的选项?或者我可能需要设置一些当地人并检查他们?我很困惑。我正在寻找这样的事情:

视图/物品/ _post.html.erb

<%= render partial: "shared/info" %>
<%#= SILLY GUESS: render partial: "shared/info", locals: { from_articles: true } %>

视图/故事/ _post.html.erb

<%= render partial: "shared/info" %>
<%#= SILLY GUESS: render partial: "shared/info", locals: { from_stories: true } %>

我该怎么办?

视图/共享/ _info.html.erb

<% if called from views/articles/_post.html.erb %>
  <p>Foo</p>
<% elsif called from views/stories/_post.html.erb %>
  <p>Bar</p>
<% end %>

1 个答案:

答案 0 :(得分:3)

params散列将始终包含:controller:action个键,但您应该使用方法controller_nameaction_name来访问这些值。你有两种选择,但第二种是更好的做法。

<% if params[:controller] == articles %>
  <p>Foo</p>
<% elsif params[:controller] == stories %>
  <p>Bar</p>
<% end %>

<% if controller_name == articles %>
  <p>Foo</p>
<% elsif controller_name == stories %>
  <p>Bar</p>
<% end %>