Rails 4 app with has_many through

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?

Try to set autosave: true on your association

Att,

[image: --]
Antonio Augusto
[image: http://]about.me/aaugusto
http://about.me/aaugusto?promo=email_sig

https://www.facebook.com/augustobr https://twitter.com/xtrdev
http://br.linkedin.com/in/antoniobr/ https://github.com/antoniosb
[image:
http://about.me/aaugusto] http://about.me/aaugusto
https://plus.google.com/u/0/111953897116031502239/

2015-04-09 0:47 GMT-03:00 Nikolay L. [email protected]:

I would test this out in the rails console first, to ensure the model
relationships are correct. Also you might want to use :
accepts_nested_attributes_for :users for your Company model

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs