2013-10-19 82 views
0

我公司控制器不能在同一時間

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

- >您需要引用在正確的上下文對象(在這種情況下複數)=

f.fields_for :users do |u| 

- >你需要建立對象在控制器之前它會呈現在表單中。添加到您的控制器:

def new 
    @company = Company.new 
    @company.users.build 
end 

這應該得到它從我所看到的

工作