gpt4 book ai didi

ruby-on-rails - 如果 rails html.erb 中的每个条件中的任何一个为真,如何仅显示一次

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:35 24 4
gpt4 key购买 nike

在我的 html.erb 文件中:

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

问题是我只想显示

你有 friend 请求来自:

如果有任何匹配项,一次,而目前它每次都会显示 status == "requested".

最佳答案

因为您似乎加载了所有对象,所以让我们在 ruby​​ 中执行此操作,否则应该使用范围来完成。

在你的模型中:

def requested?
status == 'requested'
end

在你的 Controller 中:

@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 查询

关于ruby-on-rails - 如果 rails html.erb 中的每个条件中的任何一个为真,如何仅显示一次 <p>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19205928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com