rails 使用三个参数连接两个表

rails joining two tables using three params

首先我正在使用 Psql,如果有帮助,可能没关系。

我有两个 table,(它们之间有模型 has_many)

# models
RegUser(id, Email, Name)
Booking(id , Event_id, Reg_user_id)

我如何将这两个链接在一起,以便在查看事件 40 时,该事件的注册用户将显示,它基本上是通过传递的参数将两个 table 连接在一起(我相信!!!)

这是我过去使用的代码

@reg_usr = RegUser.where(event_id: params[:id])

我们将 event_id 移动到另一个 table 并将其从注册用户 table 中删除。

你应该有以下关系:

class Event < ActiveRecord::Base
  has_many :bookings
  has_many :reg_users, through: :bookings

class RegUser < ActiveRecord::Base
  has_many :bookings
  has_many :events, through: :bookings

class Booking < ActiveRecord::Base
  belongs_to :event
  belongs_to :reg_user

然后你可以简单地做:

@event = Event.find(params[:id])
@reg_users = @event.reg_users # returns the reg_users associated to the Event