我从rails开始,我有一个我无法解决的错误。
错误- param丢失或值为空: 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>发布于 2016-06-05 06:59:06
缺少param或值为空: personas_x_tipos_persona
问题在于这行@personas_x_tipos_personas = Persona.new(tipos_personas_params)(实际上这并不需要),它正在调用tipos_personas_params。
从require(key)的文档里,
当传递一个键时,如果它存在并且它的关联值是存在的,或者它的值为false,则返回所述值。 否则引发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
endhttps://stackoverflow.com/questions/37639138
复制相似问题