I need to make an application in which there are two models: User and Company. In this case, users may be employees of the company, and then the user must be associated with Company model, and if the user is not an employee of the company, the connection with the Company model should not be.
I'm trying to make it through the association has_many through:
Models:
# == Schema Information
#
# Table name: companies
#
# id :integer not null, primary key
# name :string
# created_at :datetime not null
# updated_at :datetime not null
#
class Company < ActiveRecord::Base
has_many :company_users
has_many :users, through: :company_users
end
# == Schema Information
#
# Table name: users
#
# id :integer not null, primary key
# first_name :string
# last_name :string
# email :string
# created_at :datetime not null
# updated_at :datetime not null
#
class User < ActiveRecord::Base
has_many :company_users
has_many :companies, through: :company_users
end
# == Schema Information
#
# Table name: company_users
#
# id :integer not null, primary key
# company_id :integer
# user_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class CompanyUser < ActiveRecord::Base
belongs_to :company
belongs_to :user
end
Companies controller
class CompaniesController < ApplicationController
def signup
@company = Company.new
@user = @company.users.build
end
def create
@company = Company.new(company_params)
@company.save
end
private
def company_params
params.require(:company).permit(:name, users_attributes: [:first_name, :last_name, :email])
end
end
signup.html.erb
<%= form_for(@company) do |f| %>
<%= f.text_field :name %>
<%= f.fields_for(@user) do |user_f| %>
<%= user_f.text_field :first_name %>
<%= user_f.text_field :last_name %>
<% end %>
<%= f.submit %>
<% end %>
But it does not work. Saved only instance of the model of the Company. How to association must be made in the models, and as should be done in the controller action Companies in creating a company with an employee?