简体   繁体   中英

rails joining two tables using three params

First things first i'm using Psql, If that helps, Probably doesnt matter.

I have two tables, (they have the model has_many inbetween)

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

How do i go about linking these two together so that when viewing event 40, The registered users for that event will show, Its basically joining two two tables together from the params passed through (i believe!!!)

Heres the code i had working in the past

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

We moved the event_id to another table and dropped it out of the reguser table.

You should have the following relations:

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

And then you can simply do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM