将用户和员工与Rails 5.2和Devise相关联

时间:2018-10-02 15:54:25

标签: ruby-on-rails devise

在我的应用程序中,我遇到以下情况: 公司有用户和员工 每个用户都是一个员工,但不是每个员工都是一个用户(但可以是) Rails的实现方式是什么?


Company.rb

class Company < ApplicationRecord
  has_many :users
  has_many :employees

User.rb

class User < ApplicationRecord
  belongs_to :company

Employee.rb

class Employee < ApplicationRecord
  belongs_to :company

1 个答案:

答案 0 :(得分:1)

我认为您要做的是将员工与公司关联,将用户与员工关联,然后使用has_many_through连接公司和用户。

company.rb

class Company < ApplicationRecord
  has_many :employees
  has_many :users, through: :employees
end

employee.rb

class Employee < ApplicationRecord
  belongs_to :company
  has_one :user
end

user.rb

class User < ApplicationRecord
  belongs_to :employee
end

因此,您可以这样做:

> c = Company.create(name: 'Test') # id: 1
> e1 = c.employees.create(name: 'Test1') # id: 1
> e2 = c.employees.create(name: 'Test2') # id: 2
> u = User.create(email: 'test1@test.com', employee_id: 1) # id: 1

> u.employee # <Employee: {id: 1}>
> e1.user # <User: {id: 1}>
> e2.user # nil

> c.employees # [<Employee: {id: 1}>, <Employee: {id: 2}>]
> c.users # [<User: {id: 1}>]