gpt4 book ai didi

ruby-on-rails - 从 has_many belongs_to 查询中排除当前对象

转载 作者:行者123 更新时间:2023-12-02 01:25:01 24 4
gpt4 key购买 nike

一只鞋有_很多 socks 。 socks 属于鞋子。

我想使用 socks Controller 与 shoes 具有相同 parent_id 的 sibling 进行比较。

SocksController
def show
@sock = Sock.find(params[:id])
@shoe = Shoe.find(@sock.shoe_id)
@socks = @shoe.socks
end

socks - show.html.erb

  <% @socks.each do |sock| %>
<%= link_to sock.sock_name %>
<% end %>

当然,我会在 show.html.erb 中获取所有 socks ,但我想从 @socks = @shoe.socks 中排除我当前的 socks 。有没有办法做到这一点?我现在正在探索 where.not 选项,但以前从未尝试过。

另外,我最初的 def show 本身有什么问题吗?我认为这没问题,但感觉我在通话中是多余的,而且我可以简化它以减少查询。

最佳答案

如果你想在 View 中排除你当前的 socks ,你可以这样做。

    <% @socks.each do |sock| %>
<% next if sock.id == @sock.id %>
<%= link_to sock.sock_name %>
<% end %>

关于ruby-on-rails - 从 has_many belongs_to 查询中排除当前对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37668448/

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