我的公司财务总监
class CompaniesController < ApplicationController
def index
@companies = Company.all
end
def create
@company = Company.create(company_params)
render :action => 'index'
end
private
def company_params
params.require(:company).permit(:name, :users_attributes => [:id, :email, :password, :password_confirmation])
end
end
公司模式
class Company < ActiveRecord::Base
has_many :users
accepts_nested_attributes_for :users
end
用户模型
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
belongs_to :company
end
查看模板
= form_for :company, :html => {:class => 'form-horizontal', :role => 'form'} do |f|
.form-group
%label{:for => 'inputName', :class => 'col-lg-3 control-label'} Company Name :
.col-lg-9= f.text_field :name, :class => 'form-control', :placeholder => 'Enter Company Name'
= f.fields_for :user do |u|
.form-group
%label{:for => 'inputEmail', :class => 'col-lg-3 control-label'} User Email :
.col-lg-9=u.email_field :email, :class => 'form-control', :placeholder => 'Enter Email Address'
.form-group
%label{:for => 'inputPassword', :class => 'col-lg-3 control-label'} Password :
.col-lg-9=u.password_field :password, :class => 'form-control', :placeholder => 'Enter Password'
.form-group
%label{:for => 'inputPasswordConfirmation', :class => 'col-lg-3 control-label'} Confirm Password :
.col-lg-9=u.password_field :password_confirmation, :class => 'form-control', :placeholder => 'Re-Enter Password'
.col-lg-offset-6= f.submit :class => 'btn btn-default'
我正在尝试一次性创建关联公司和用户记录。我无法理解这里的错误
答案 0 :(得分:0)
- &GT;您需要在正确的上下文中引用该对象(在本例中为复数)=
f.fields_for :users do |u|
- &GT;您需要在控制器中构建对象,然后才能在表单中进行渲染。将其添加到您的控制器:
def new
@company = Company.new
@company.users.build
end
这应该让我能够看到它的工作