我创建了一个表单视图来保存其他表中的id但是没有工作并保存NULL。
这是我的表格:
|purchase_products|
|id| |name| #A.I (AUTO INCREMENT IN 1)
A.I varchar(255)
1 ABC
2 DEF
|supplier_products|
|id| |purchase_product| |amount|
A.I integer integer
1 2 1000
2 1 2000
这是控制器:
class PurchaseProductController < ApplicationController
def new_product
@obj_product = PurchaseProduct.new(params[:obj_product])
@obj_supplier_product = SupplierProduct.new(params[:obj_supplier_product])
end
def create_product
@obj_product = PurchaseProduct.new(params[:obj_product])
@obj_supplier_product = SupplierProduct.new(params[:obj_supplier_product])
if @obj_product.save()
@obj_supplier_product.save()
end
end
end
这是我的模特:
class PurchaseProduct < ActiveRecord::Base
has_many :supplier_products
end
class SupplierProduct < ActiveRecord::Base
belongs_to :purchase_product
end
这是我的观点
<% form_for :obj_product, :url => {:controller=>"purchase_product",:action=>'create_product'} do |f|%>
Amount:<%= text_field_tag 'obj_product[name]',@name %>
ID <%= text_field_tag 'obj_supplier_product[id]',@obj_product.id %>
<%= submit_tag "Create",:class=>"button" %>
<% end %>
这是日志:
Processing PurchaseProductController#create_product (for 127.0.0.1 at 2014-07-23 15:56:48) [POST]
Parameters: {"obj_supplier_product"=>{"purchase_product_id"=>"", "amount"=>"1800", "supplier_id"=>"6"}, "obj_product"=>{"name"=>"Impresora "}, "authenticity_token"=>"yeah", "commit"=>"Create"}
PurchaseProduct Create (0.2ms) INSERT INTO `purchase_products` (`name`) VALUES( 'Printer' )
SQL (29.9ms) COMMIT
SQL (0.1ms) BEGIN
SupplierProduct Create (0.0ms) Mysql::Error: Column 'purchase_product_id' cannot be null:
INSERT INTO `supplier_products` (`purchase_product_id`, `amount`) VALUES(NULL, 1800.0)
purchase_products中的ID未保存在supplier_products
中我尝试过但仍然没有工作:
def create_product
@obj_product = PurchaseProduct.new(params[:obj_product])
@obj_supplier_product = SupplierProduct.new(params[:obj_supplier_product])
if @obj_product.save()
@obj_product.id= @obj_supplier_product.purchase_product_id
@obj_supplier_product.save()
end
end
请有人可以帮帮我吗?
答案 0 :(得分:1)
简单方法:在控制器中更改保存逻辑:
if @obj_product.save
@obj_supplier_product.purchase_product_id = @obj_product.id
@obj_supplier_product.save
end
正确的方法:使用嵌套属性:http://railscasts.com/episodes/196-nested-model-form-part-1