错误 "param is missing or the value is empty: personas_x_tipos_persona"

Error "param is missing or the value is empty: personas_x_tipos_persona"

我从 rails 开始,我遇到了无法解决的错误..

Error - param is missing or the value is empty: personas_x_tipos_persona

控制器

class PersonasController < ApplicationController
  def create_cliente
    @cliente = Persona.new(persona_params)
    @personas_x_tipos_personas = Persona.new(tipos_personas_params)
    if @cliente.save
      redirect_to show_clientes_path
    else
      render :new_cliente
    end
  end
  private
  def persona_params
    params.require(:persona).permit(:nombre, :apellido, :direccion, :ruc, :contacto, :email)
  end
  def tipos_personas_params
    params.require(:personas_x_tipos_persona).permit(:linea_credito)
  end
end

查看

<div>
  <%= form_for :persona ,:url => add_cliente_path, :html => {:method => :post} do |f|%>
    <% @cliente.errors.full_messages.each do |message| %>
      <div class="alert alert-danger" margin-top:10px">
        * <%=message%>
      </div>
    <% end %>

    <%= f.text_field :nombre, placeholder: "Nombre del Cliente"%>
    <%= f.text_field :apellido, placeholder: "Apellido del Cliente"%>
    <%= f.text_field :direccion, placeholder: "Direccion del Cliente"%>
    <%= f.text_field :ruc, placeholder: "RUC del Cliente"%>
    <%= f.text_field :contacto, placeholder: "Contacto del Cliente"%>
    <%= f.email_field :email, placeholder: "Email del Cliente""%>

      <%= f.fields_for :personas_x_tipos_persona do |pxp|%>
        <%= pxp.number_field :linea_credito, placeholder: "Linea de Credito del Cliente"%>
      <% end %>
    <%= f.submit 'Guardar'%>
  <% end %>
</div>

param is missing or the value is empty: personas_x_tipos_persona

问题出在调用 tipos_personas_params.

的这一行 @personas_x_tipos_personas = Persona.new(tipos_personas_params)实际上不需要

来自 require(key)

的文档

When passed a single key, if it exists and its associated value is either present or the singleton false, returns said value

Otherwise raises ActionController::ParameterMissing

因此,在您的情况下,require 期望 :personas_x_tipos_persona,而 params 中缺少它,错误也是如此。

实际上,表单对象:persona而不是:personas_x_tipos_persona。另外,正如我所看到的,您正在使用 fields_for,因此您需要在 persona_params 内将 :personas_x_tipos_persona_attributes 列入白名单,并且不需要 tipos_personas_params 方法。下面的代码应该让你去。

class PersonasController < ApplicationController
  def create_cliente
    @cliente = Persona.new(persona_params)
    #this is not needed
    #@personas_x_tipos_personas = Persona.new(tipos_personas_params) 
    if @cliente.save
      redirect_to show_clientes_path
    else
      render :new_cliente
    end
  end

  private
  def persona_params
    params.require(:persona).permit(:nombre, :apellido, :direccion, :ruc, :contacto, :email, personas_x_tipos_persona_attributes: [:id, :linea_credito])
  end
end