CrescentStrike
CrescentStrike

Reputation: 23

belongs_to and has_many in rails

I'm currently working in a project in which users can add users to a company, I want to save who added each user so there would be a belongs_to relation but one user can also add multiple users so that's a has_many.

class Passenger
  belongs_to :passenger, index: true
  has_many :passengers
end

I don't know if I can do this

Upvotes: 0

Views: 81

Answers (1)

Tun
Tun

Reputation: 1447

What you need is self-jons.

# app/model/passenger.rb
class Passenger < ApplicationRecord
  has_many :creations, class_name: 'Passenger', foreign_key: :passenger_id
  belongs_to :creator, class_name: 'Passenger', optional: true
end

You should have a migration with

class CreatePassengers < ActiveRecord::Migration[5.0]
  def change
    create_table :passengers do |t|

      t.references :passenger

      # other attributes
    end
  end
end

Upvotes: 1

Related Questions