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'              

我正在尝试一次性创建关联公司和用户记录。我不明白这里出了什么问题

4

1 回答 1

0

-> 您需要在正确的上下文中引用对象(在这种情况下是复数)=

f.fields_for :users do |u|

-> 您需要在控制器中构建对象,然后才能在表单中呈现。将此添加到您的控制器:

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

从我所看到的情况来看,这应该可以正常工作

于 2013-10-19T19:10:46.483 回答