0

我的 ProductsController 中有一个创建操作(参数来自我视图中的表单):

def create
  vendor = @current_vendor
  product = Product.create(:name => params[:product][:name])
  vendor.products << product
  vendor.belongings.create(:product_id => product.id, :count => params[:belonging][:count], :detail => params[:belonging][:detail])
  if vendor.save
    flash[:notice] = "Produkt hinzugefügt!"
    redirect_back_or_default root_url
  else
    render :action => :new
  end
end
  1. 它创建一个变量“vendor”,它存储当前登录的供应商(Authlogic)
  2. 创建一个新产品(产品名称来自表单中的输入字段)并存储在变量“产品”中
  3. “产品”正在连接到当前供应商
  4. 在财物表中,正在存储产品的附加信息
  5. 它保存了整个事情

这是通过财物表的多对多关系。

我的问题是,创建操作总是创建产品两次!

谢谢你的帮助!:)

当我通过表单创建新对象时,我的控制台日志是:

Started POST "/products" for 127.0.0.1 at 2013-09-15 20:40:26 +0200
Processing by ProductsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"lNk/qQMP0xhlCuGgHtU+d5NEvIlCFcPSKB0FxDZH0zY=", "product"=>{"name"=>"Erdbeeren"}, "belonging"=>{"count"=>"20", "detail"=>"Rot"}, "commit"=>"Create"}
DEPRECATION WARNING: ActiveRecord::Base#with_scope and #with_exclusive_scope are deprecated. Please use ActiveRecord::Relation#scoping instead. (You can use #merge to merge multiple scopes together.). (called from current_vendor_session at /Users/reto_gian/Desktop/dici/app/controllers/application_controller.rb:11)
  Vendor Load (0.3ms)  SELECT "vendors".* FROM "vendors" WHERE "vendors"."persistence_token" = '04f75db0e2ef108ddb0ae1be1da167536d47b4d79c60ecb443ad2ea5717ecd752388e581f9379746568c72372be4f08585aa5581915b1be64dc412cded73a705' LIMIT 1
   (0.1ms)  begin transaction
  SQL (0.8ms)  INSERT INTO "products" ("created_at", "name", "updated_at") VALUES (?, ?, ?)  [["created_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["name", "Erdbeeren"], ["updated_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00]]
   (0.8ms)  commit transaction
   (0.1ms)  begin transaction
  SQL (0.6ms)  INSERT INTO "belongings" ("created_at", "product_id", "updated_at", "vendor_id") VALUES (?, ?, ?, ?)  [["created_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["product_id", 7], ["updated_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["vendor_id", 1]]
   (0.9ms)  commit transaction
   (0.1ms)  begin transaction
  SQL (0.6ms)  INSERT INTO "belongings" ("count", "created_at", "detail", "product_id", "updated_at", "vendor_id") VALUES (?, ?, ?, ?, ?, ?)  [["count", "20"], ["created_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["detail", "Rot"], ["product_id", 7], ["updated_at", Sun, 15 Sep 2013 18:40:26 UTC +00:00], ["vendor_id", 1]]
   (0.9ms)  commit transaction
Redirected to http://localhost:3000/
Completed 302 Found in 30ms (ActiveRecord: 5.1ms)
4

1 回答 1

0

我认为问题可能出在

vendor.products << product

这是添加变量product(这是Product.create(:name => params[:product][:name])第二vendor.products次 - 这是不必要的,可能是您问题的根源

于 2013-09-15T18:46:41.777 回答