在嵌套表单上键入错误

时间:2018-01-21 04:58:52

标签: ruby-on-rails forms parameters

在这张桌子上敲打着我的头。我有另一个嵌套的形式,但这个让我发疯。

错误是:

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

控制器:

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

在new.html.erb上:

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

此代码看起来与我拥有的另一个嵌套设置完全相同,但它有效:p

我读过有时会改变params =&gt;只是有一个分号工作,但替换user_attributes =&gt;使用user_attributes:没有改变任何内容。

编辑: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 %>

1 个答案:

答案 0 :(得分:0)

在表单上使用users代替users_attributes

不要忘记在模型accepts_nested_attributes_for :users

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

我想知道为什么你没有:users直接加入form