创建操作始终创建两个相同的表条目而不是一个

时间:2013-09-15 17:56:34

标签: ruby-on-rails ruby many-to-many rails-activerecord

我的ProductsController中有一个创建动作(params来自我视图中的一个表单):

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. 创建一个变量&#34; vendor&#34;,存储当前登录的供应商(Authlogic)
  2. 创建一个新产品(产品名称来自表单中的输入字段)并存储在变量&#34; product&#34;
  3. &#34;产品&#34;正在连接到当前的供应商
  4. 在所有物表中,存储了产品的其他信息
  5. 它保存了整件事
  6. 这是所有物品表中的多对多关系。

    我的问题是,创建操作始终会创建产品两次!

    感谢您的帮助! :)

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

    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)
    

1 个答案:

答案 0 :(得分:0)

我认为问题可能出在

vendor.products << product

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