我需要製作一個應用程序,其中有兩個模型:用戶和公司。在這種情況下,用戶可能是公司的僱員,然後用戶必須與公司模型相關聯,並且如果用戶不是公司的員工,則與公司模型的連接不應該是。Rails 4應用程序has_many通過
我試圖通過使它通過協會的has_many:
型號:
# == 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
公司控制器
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 %>
但它沒有工作。只保存公司模型的實例。 如何在模型中進行關聯,以及在控制器操作中應該如何完成公司與員工創建公司?
是的,但我需要的關係模型作爲一個獨立的實體工作。 –
在這種情況下,我相信你需要嵌套你的嵌套屬性。我用一個例子更新了我的答案 – noah