gpt4 book ai didi

ruby-on-rails - 如何在 Ruby on the Rails 查询中使用外键?

转载 作者:行者123 更新时间:2023-11-29 13:17:05 26 4
gpt4 key购买 nike

我有三个模型; 事件用户条目。我希望在我的用户页面上能够检索与与用户关联的事件相关的事件相关的信息。

def show
@user = User.find(params[:id])
@entry = @user.entries.paginate(page: params[:page])
end

它对 @user.entries.count 非常满意,但我想在表中链接如下:

事件名称 - 事件地点 - 类(class)

我的模型如下:

class Event < ApplicationRecord
has_many :entries, dependent: :destroy

class User < ApplicationRecord
has_many :entries, dependent: :destroy

class Entry < ApplicationRecord
belongs_to :user
belongs_to :event

最佳答案

如果它们是相关的:

class User < ApplicationRecord
has_many :events
end

class Event < ApplicationRecord
has_many :entries
belongs_to :user
end

class Entry < ApplicationRecord
belongs_to :event
end

然后您可以使用从 Entry 开始的连接,直到 User 并检查用户 ID 是您需要的事件:

Entry.joins(event: :user).where(users: { id: user_id })

关于ruby-on-rails - 如何在 Ruby on the Rails 查询中使用外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47641693/

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