我有一个处理2个模型的表单,Vehiculo和Poliza。这就是我现在设置它们的方式:
class Vehiculo < ActiveRecord::Base
has_one :poliza
end
class Poliza < ActiveRecord::Base
belongs_to :vehiculo
end
Vehiculo上的create方法如下所示:
def create
@vehiculo = Vehiculo.new(params[:vehiculo])
@polizadeseguro = Polizadeseguro.new(params[:poliza])
respond_to do |format|
if @vehiculo.save #&& @poliza.save
format.html { redirect_to(@vehiculo, :notice => 'Vehiculo was successfully created.') }
format.xml { render :xml => @vehiculo, :status => :created, :location => @vehiculo }
else
format.html { render :action => "new" }
format.xml { render :xml => @vehiculo.errors, :status => :unprocessable_entity }
end
end
/ vehiculos / new上的表单有一个@fields_for部分,其中包含来自poliza的字段。当我提交表单时,它会保存所有字段,但它不会将刚刚创建的来自vehiculo的id分配给Polizas表上的vehiculo_id。在网上阅读了很多关于这个的问题之后,它似乎应该根据模型上的关系“自动地”保存它。这是真的?如果是这样,为什么它不起作用?如果没有,我需要添加到create方法中,以便解决这个问题?
谢谢!
更新: 用json作为输出更新create方法后,我得到的是:
{
"utf8"=>"✓",
"authenticity_token"=>"tEhNC4J17h+KvNgXv1LLkVyufQwU2uAT18P7msQxiqA=",
"vehiculo"=>{
"marca_id"=>"2",
"modelo_id"=>"4",
"color"=>"Blanco",
"ano"=>"2011",
"chassis"=>"123456789",
"placa"=>"G123456",
"cliente_id"=>"1",
"entaller"=>"0",
"vip"=>"0"
},
"poliza"=>{
"compania"=>"Comp1",
"numeropoliza"=>"736458",
"vencimiento(1i)"=>"2011",
"vencimiento(2i)"=>"9",
"vencimiento(3i)"=>"21"
}
}
这是输出,所以至少从表单中获取字段,但它没有将它们插入到polizas表中。
答案 0 :(得分:1)
您需要确保您的父模型接受子模型的嵌套属性:
class Vehiculo < ActiveRecord::Base
has_one :poliza
accepts_nested_attributes_for :poliza
end
假设您的表单设置正确,您的params
将如下所示:
params = {
:vehiculo => {
:field => "value",
:another_field => "value",
:poliza => {
:poliza_field => "poliza value"
}
}
}
所以你在控制器中应该需要的是:
def create
@vehiculo = Vehiculo.new(params[:vehiculo])
respond_to do |format|
if @vehiculo.save #&& @poliza.save
format.html { redirect_to(@vehiculo, :notice => 'Vehiculo was successfully created.') }
format.xml { render :xml => @vehiculo, :status => :created, :location => @vehiculo }
else
format.html { render :action => "new" }
format.xml { render :xml => @vehiculo.errors, :status => :unprocessable_entity }
end
end
end
<强> [更新] 强>
以下是您需要完成的所有工作。
如上所述,您需要accepts_nested_attributes_for
。
接下来,确保您的新操作正在构建孩子。
class VehiculosController < ApplicationController
def new
@vehiculo = Vehiculo.new
@vehiculo.build_poliza
end
def create
vehiculo = Vehiculo.new(params[:vehiculo])
if vehiculo.save
redirect_to root_path, :notice => "Success"
else
redirect_to root_path, :alert => "Failure"
end
end
end
最后,在您的视图中,使用fields_for :child_model
引用子模型,如下所示:
<%= form_for @vehiculo do |f| %>
<p>Whatever Field: <%= f.text_field :whatever %></p>
<%= f.fields_for :poliza do |p| %>
<p>Polizo Field: <%= p.text_field :something %></p>
<% end %>
<% end %>