Why does the CompaniesController not create a record CompanyUser with current_user.companies.build(company_params)
?
How can I create CompanyUser record at the time of creation of the Company record?
Models:
User
class User < ApplicationRecord
has_many :company_users, dependent: :destroy
has_many :companies, through: :company_users
end
Company
class Company < ApplicationRecord
include Userstampable::Stampable
has_many :company_users, dependent: :destroy
has_many :users, through: :company_users
accepts_nested_attributes_for :company_users, reject_if: :all_blank
validates :name, presence: true, length: { maximum: 100 }
validates :description, length: { maximum: 1000 }
end
CompanyUser
class CompanyUser < ApplicationRecord
include Userstampable::Stampable
belongs_to :company
belongs_to :user
validates :company_id, presence: true
validates :user_id, presence: true
end
CompaniesController
class CompaniesController < ApplicationController
def create
@company = current_user.companies.build(company_params)
respond_to do |format|
if @company.save
format.html { redirect_to @company, notice: 'Company was successfully created.' }
format.json { render :show, status: :created, location: @company }
else
format.html { render :new }
format.json { render json: @company.errors, status: :unprocessable_entity }
end
end
end
private
# Never trust parameters from the scary internet, only allow the white list through.
def company_params
params.require(:company).permit(:name, :description)
end
end
Migrate
class CreateCompanyUsers < ActiveRecord::Migration[6.0]
def change
create_table :company_users do |t|
t.integer :role, default: 0
t.belongs_to :company, null: false, foreign_key: true
t.belongs_to :user, null: false, foreign_key: true
t.timestamps null: false, include_deleted_at: true
t.userstamps index: true, include_deleter_id: true
t.index [:company_id, :user_id], unique: true
end
end
end