【问题标题】:Type error on nested form嵌套表单上的类型错误
【发布时间】:2018-01-21 04:58:52
【问题描述】:

一直在用我的头撞到这张桌子上。我有另一个嵌套表单,但这个让我发疯。

错误是:

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

我读过有时将参数从 => 更改为仅使用分号有效,但将 user_attributes => 替换为 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 %>

【问题讨论】:

  • 请给我看看你的_form.html.erb
  • 你说类型错误在 RegistrationsController 但你发布了 CompaniesController
  • 已添加表单。谢谢!
  • 已修复:将正确的 _form.html.erb 放在帖子上

标签: ruby-on-rails forms parameters


【解决方案1】:

在表单上使用users 而不是users_attributes

别忘了在模型Company中定义accepts_nested_attributes_for :users

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

不知道你为什么不把:users直接放到form

【讨论】:

  • 将其更改为 ":users" 会导致表单的用户部分不显示在页面上。我在控制器中改变和不改变它。
  • 快速更改,我将其更改为单数用法(:user vs :users)并显示在页面上。但我仍然收到类型错误
  • 因为“@company”没有用户。为此,在新操作中,您需要构建它:“@company.users.build”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多