简体   繁体   中英

Type error on nested form

been banging my head on the table over this one. I have another nested form but this one is driving me crazy.

The error is:

TypeError in CompaniesController#create
no implicit conversion of Symbol into Integer
@company = Company.new(company_params)

The controller:

class CompaniesController < ApplicationController
  layout 'welcome'

  def new
    @company = Company.new
  end

  def create
    @company = Company.new(company_params)

    if @company.save
      flash[:notice] = "New company created successful."
      redirect_to admin_accounts_path
    else
      flash.now[:alert] = "Creation failed, please try again"
      render :new
    end
  end

  private

  def company_params
    params.require(:company).permit(:name, :location, :users_attributes => [:email, :password])
  end
end

On the new.html.erb:

  <%= render partial: 'form', locals: { company: @company, users_attributes: :users_attributes } %>

This code looks exactly like another nested setup I have, but it works :p

I had read that sometimes changing the params from => to just having a semicolon works, but replacing the user_attributes => with a user_attributes: didn't change anything.

EDIT: form.html.erb

<%= form_for company, url: companies_path do |f| %>
  <div class="col-12">
    <div class="row">
      <div class="col p-0 mr-3">
        <div class="form-group">
          Company <%= f.label :name %>
          <%= f.text_field :name, :placeholder => 'Company name', class: 'form-control' %>
        </div>
        <div class="form-group">
          <%= f.label :location %>
          <%= f.text_field :location, :placeholder => 'Location', class: 'form-control' %>
        </div>
      </div>
      <div class="col p-0">
        <%= f.fields_for users_attributes do |user_f| %>
          <div class="form-group">
            <%= user_f.label :email %>
            <%= user_f.text_field :email, :placeholder => 'Your Email Address', class: 'form-control' %>
          </div>
          <div class="form-group">
            <%= user_f.label :password %>
            <%= user_f.password_field :password, :placeholder => 'Password', class: 'form-control' %>
          </div>
        <% end %>
      </div>
      <div class="col-12 p-0">
        <%= f.submit "Sign-Up", :class => 'btn btn-primary btn-block btn-lg' %>
      </div>
    </div>
  </div>
<% end %>

Use users instead of users_attributes on the form.

Don't forget to define accepts_nested_attributes_for :users in model Company

## new.html.erb
<%= render partial: 'form', locals: { company: @company, users_attributes: :users } %>

I wonder why you didn't put :users into the form directly

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