mardi 14 avril 2020

has_many through create joint table with attributes

In my Rails app there are 3 model:

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

In console I'm able to create a joint table (Roles) with person_id and company_id, however I as well have job_title field I want to pass value during creation.

That's how I create joint table:

person = Person.find(id)
person.companies.create(legal_name: "Company name Ltd.")

As a result I get:

#<Role id: 1, person_id: 2, company_id: 25, job_title: nil>

Job title is nil and I want to populate this attribute with data during creation.

How I do something like this?

person = Person.find(id)
person.companies.create(legal_name: "Company name Ltd.", roles: [job_title: "Job title"])

Aucun commentaire:

Enregistrer un commentaire