0

我正在挑战 Rails 中一个恼人的问题。

我有一个视图,我正在尝试渲染一个部分,但只有在@prev_activity != message.about这样的时候:

<%= @prev_activity != message.about ? render(:partial => "dashboards/stream_activity", :locals => { :activity => message.about }) : render(:text => "")  %>

在dashboards/_stream_activity.html.erb 中,我渲染了一些内容并设置了先前的活动变量:

<% @prev_activity = activity %>

它不起作用,因为在@prev_activity != message.about检查 rails render dashboards/_stream_activity.html.erb 之前,@prev_activity它等于message.about.

有没有办法解决这个问题?

4

4 回答 4

0

尝试

 <%= render(:partial => "dashboards/stream_activity",:locals => 
                        { :activity => message.about }) 
                        if @prev_activity != message.about %>
于 2013-01-10T08:51:28.233 回答
0

如果您不使用三元运算符,您的问题可能会消失:

<% if @prev_activity != message.about %>
  <%= render(:partial => "dashboards/stream_activity", :locals => { :activity => message.about }) %>
<% else %>
  <%= render(:text => "") %>
<% end %>

(最好将此功能放在视图辅助方法中)

于 2013-01-10T08:54:04.740 回答
0

保留您的变量集代码,即<% @prev_activity = activity %>在部分调用之前。例如,将该代码保存在调用控制器中,然后进行部分渲染。例如 -

def myactivity
  // your code
  @prev_activity = activity
  render("dashboards/stream_activity",:locals => { :activity => message.about }) 
  if @prev_activity != message.about
end
于 2013-01-10T09:15:52.747 回答
0

我终于找到了解决方案。鉴于我在哪里渲染我设置的@prev_activity集合nil

<% @prev_activity = nil %>
<%= render :partial => "dashboards/stream_message", :collection => @workspace_stream.messages %>

比在仪表板/_stream_message.html.erb 中的预期工作方式:

<% if @prev_activity != message.about %>
  <%= render partial: "dashboards/stream_activity", locals: { activity: message.about }%>
<% end %>

仪表板/_stream_activity.html.erb:

<% @prev_activity = activity %>

在控制器中设置@prev_activitynil效果不如此处发布的所有其他解决方案。

于 2013-01-10T09:48:36.737 回答