1

我有一个处理 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 表中。

4

1 回答 1

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 %>
于 2011-04-03T04:04:27.560 回答