在我的 Rails 应用程序中有 3 个模型:
class Person < ApplicationRecord
has_many :roles
has_many :companies, through: :roles
end
class Company < ApplicationRecord
has_many :roles
has_many :people, through: :roles
end
class Role < ApplicationRecord
belongs_to :person
belongs_to :company
end
在控制台中,我可以使用 person_id 和 company_id 创建一个联合表(角色),但是我也有 job_title 字段,我想在创建过程中传递值。
这就是我创建联合表的方式:
person = Person.find(id)
person.companies.create(legal_name: "Company name Ltd.")
结果我得到:
#<Role id: 1, person_id: 2, company_id: 25, job_title: nil>
职位为 nil,我想在创建期间用数据填充此属性。
我怎么做这样的事情?
person = Person.find(id)
person.companies.create(legal_name: "Company name Ltd.", roles: [job_title: "Job title"])