gpt4 book ai didi

ruby-on-rails - 遍历 has_many 时访问关联的连接模型 :through association

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

我觉得这是一个非常基本的问题,但出于某种原因我被它难住了(Rails 新手)并且似乎无法找到答案(这可能是我没有正确搜索)。

所以我有一个基本的 has_many :through 这样的关系:

class User < ApplicationRecord
has_many :contacts, through :user_contacts

class Contact < ApplicationRecord
has_many :users, through :user_contacts

在 users/show.html.erb 中,我正在遍历单个用户的联系人,例如:

<% @user.contacts.each do |c| %>
<%= c.name %>
<% end %>

现在在每个循环中,我想访问与给定用户和联系人相关联的 user_contact 连接模型,以便显示 created_at 时间戳,该时间戳指示用户 <--> 建立联系关系的时间。

我知道我可以调用 UserContact.find 来通过 user_id 和 contact_id 在数据库中查找模型,但不知何故这感觉是多余的。如果我正确理解这是如何工作的(我完全有可能不理解),当我已经从数据库中加载给定用户及其联系人时,应该已经加载了 user_contact 模型。我只是不知道如何正确访问正确的模型。有人可以帮助正确的语法吗?

最佳答案

实际上连接模型还没有被加载:ActiveRecord 使用 through 规范来构建它的 SQL JOIN 语句来查询正确的 Contact 记录但实际上只会实例化那些。

假设您有一个 UserContact 模型,您可以这样做:

@user.user_contacts.includes(:contact).find_each do |uc|
# now you can access both join model and contact without additional queries to the DB
end

如果你想保持内容的可读性而不用 uc.contact.something 弄乱你的代码,你可以在 UserContact 模型中设置委托(delegate),将一些属性委托(delegate)给 contactuser 分别。比如这个

class UserContact < ActiveRecord::Base
belongs_to :user
belongs_to :contact
delegate :name, to: :contact, prefix: true
end

可以让你写

uc.contact_name

关于ruby-on-rails - 遍历 has_many 时访问关联的连接模型 :through association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39110764/

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