简体   繁体   中英

rails joining two tables together using has oen and has many

So I'm trying to link two models together

currently, I have tickets for events.

in the event model, I'm under the understanding that one event has one or more tickets so that would be a has many ?

and in the tickets table, it would have one event?

In the tickets table, I have the event_id column.

Basically what I've wanting to have is the ability to type event.tickets.each for example to return all the tickets in the event

event.rb model

class Event < ActiveRecord::Base
  has_many :tickets
end

ticket.rb model

class Ticket < ActiveRecord::Base
  belongs_to :event
end

to fetch tickets of event do like below

event  = Event.first
event.tickets.each do |ticket|
  puts ticket.inspect
end

in ticket model add has_many :events in event model add belongs_to :ticket

your events table should have a ticket_id foreign key.

this way you can do event.ticket and also ticket.events

that is all :)

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