[英]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.我目前正在一个项目中,用户可以将用户添加到公司,我想保存谁添加了每个用户,这样就会有一个属于关联的关系,但一个用户也可以添加多个用户,所以这是一个 has_many。
class Passenger
belongs_to :passenger, index: true
has_many :passengers
end
I don't know if I can do this我不知道我是否可以做到这一点
What you need is self-jons .你需要的是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.