【问题标题】:Rails Partials For Resources资源的 Rails 部分
【发布时间】:2014-06-14 10:26:40
【问题描述】:
我的应用程序中有一个名为“练习”的资源。我目前有一个名为 _exercise.html.erb 的部分,我用它来渲染它们。我有一个偏远的案例,我想以一种截然不同的方式呈现它们。我可以为具有这种其他格式的练习制作另一个部分,并且仍然能够使用 吗?
如果不是最好的方法是什么?我是否应该在控制器中输出一个变量来告诉部分使用哪个布局,这将在一个文件中同时具有一个布局和一个如果来决定。还是有更好的办法?
【问题讨论】:
标签:
ruby-on-rails
partials
【解决方案1】:
如果您想使用业务逻辑来确定何时显示您的 @exercises 集合的哪个部分,您应该使用练习模型中的 to_partial_path 方法来定义它。请参阅这篇文章中的 #4:http://blog.plataformatec.com.br/2012/01/my-five-favorite-hidden-features-in-rails-3-2/
或者,如果这更多是与视图相关的决定(即,一个视图将始终使用常规的 _exercises.html.erb,而另一个视图将始终使用例如 _alternate_exercises.html.erb),那么您可以这样指定:
<%= render partial: 'alternate_exercises', collection: @exercises, as: :exercise %>
这将为@execrises 中的每个项目呈现一次_alternate_exercises.html.erb 部分,并通过名为exercise 的local_assign 将该项目传递给部分。
【解决方案2】:
在这种情况下,我想你有两个选择:
1) 将条件代码放在_exercises.html.erb中
例如。
<% if @exercise.meets_some_condition %>
you see this stuff
<% else %>
you see other stuff
<% end %>
这样,你仍然可以使用
2) 否则,您的另一个选择是拥有单独的部分并将它们呈现在外面。
例如。
<% @exercises.each do |exercise| %>
<% if exercise.meets_some_condition %>
<%= render "exercises/some_condition_exercise" %>
<% else %>
<%= render "exercises/exercise" %>
<% end %>
<% end %>
【解决方案3】:
这是渲染局部的最佳方法。您可以在代码中使用 if else 语句包装该部分。这是我的例子
使用名为 _victim.html.erb 的表单进行渲染
<%= render :partial => "victim", :locals => {:f => f }%>
无格式渲染
<%= render :partial => "victim"%>