在我的html.erb文件中:

<% @user.relationships.each do |relationship| %>
  <% if relationship.status == "requested" %>
    <p>You have friend requests from: </p>
    <%= User.find(relationship.followed_id).name %>

问题是我只想显示youhavefriendrequests from:如果有任何匹配项,则显示一次,而当前它会在每次状态为“requested”时显示。

最佳答案

因为您似乎加载了所有对象,所以让我们用ruby来完成,否则应该使用一个作用域来完成。
在您的模型中:

def requested?
  status == 'requested'
end

在控制器中:
@relationships = @user.relationships.includes(:followed)
@requested_relationships = @relationships.select &:requested?

在您看来:
<% if @requested_relationships.any? %>
  <p>You have friend requests from: </p>
    <% @requested_relationships.each do |relationship| %>
       <%= relationship.followed.name %>

编辑以防止n+1查询

10-08 04:38