【发布时间】:2015-04-08 04:15:29
【问题描述】:
我需要制作一个有两种模型的应用程序:用户和公司。在这种情况下,用户可能是公司的员工,那么用户必须与公司模型关联,如果用户不是公司的员工,则不应与公司模型关联。
我正在尝试通过关联 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 %>
但它不起作用。仅保存了公司模型的实例。 必须如何在模型中进行关联,以及在控制器操作中应该如何进行公司与员工创建公司?
【问题讨论】:
标签: ruby-on-rails-4 associations nested-attributes has-many-through