简体   繁体   中英

Not able to create multiple associated model records at the same time

My Companies Controller

  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

Companies Model

class Company < ActiveRecord::Base
  has_many :users
  accepts_nested_attributes_for :users
end

User Model

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

View Template

= 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'              

I am trying to create a associated company and user record in one go. I can't understands whats wrong out here

-> You need to reference the object in the correct context (plural in this case) =

f.fields_for :users do |u|

-> You need to build the object in your controller before it will render in the form. Add this to your controller:

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

That should get it working from what I can see

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM