如何在Ruby中使用Ruby的外国钥匙



我有三个模型;事件用户条目。我希望在我的用户页面上找到与与用户相关的事件相关的事件有关的信息。

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

它对@user.entries.count很满意,但我想在桌子中链接到这样的东西:

事件名称 - 事件位置 - 课程

我的模型是波纹管:

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

然后,您可以使用从输入开始,到用户开始并检查用户ID是您需要的事件的事件:

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

最新更新