您可以只渲染特定动作的一部分吗?

Can you render only part of a partial for a particular action?

我有一个项目部分,其中包含项目图片、项目价格和项目描述等内容。在部分项目中,我还有一个用户头像的小缩略图,因为它是一个 p2p 市场。我希望这个头像呈现在我 <%= render @items %> 的任何地方,除了用户个人资料页面(用户控制器,显示操作),我希望它停止,因为它是多余的。

有没有办法做到这一点?我已经尝试了很多东西,但还差得远。谢谢你的帮助。

这是项目的部分代码:

<div class="thumbnail">
          <%= link_to item_path(item) do %>
          <%= image_tag(item.image.url(:thumb)) %>
          <% end %>
      </div>

      <div class="caption">
        <% if item.user.avatar.url %>
          <%= link_to item.user do %>
            <%= image_tag(item.user.avatar.url(:thumb), class: "user-avatar-partial pull-left") %>
          <% end %>
        <% else %> 
          <%= link_to item.user do %>
            <%= image_tag 'avatar-thumb.png', class: "user-avatar-partial pull-left" %>
          <% end %>
        <% end %>
          <span id="item-name-partial"> 
            <%= link_to item_path(item) do %>
              <%= item.name.truncate(20) %>
            <% end %>
          </span>
            <span class="pull-right" id="item-price-partial"> 
              <%= link_to item_path(item) do %>
                <%= number_to_currency item.price %>
              <% end %>
            </span>
      </div> 

我可以想到两种解决方案,但在这两种解决方案中,您都必须稍微修改部分代码。

解决方案一:

在控制器操作中设置一个实例变量并在您的部分中使用它。

class UsersController
  def show
    @hide_small_thumbnail = true
    # rest of your code
  end
end

然后在你的部分:

<% unless @hide_small_thumbnail %>
  <% #code for showing the thumbnail %>
<% end %>

除该特定操作外,实例变量的值将为 nil,因此您的缩略图将按原样显示。

方案二:

在您的视图中指定控制器和操作名称。例如:

<% condition_one = (controller.controller_name == 'users') %>
<% condition_two = (controller.action_name == 'show') %>
<% unless condition_one && condition_two %>
  <% #code for showing the thumbnail %>
<% end %>

如果一定要我选的话,我会选择第一个。但如果你选择后者,在你看来,最好将条件移动到辅助方法并使用辅助方法,而不是详细条件。