0

我正在使用piggybak gem

我有一个产品q

1.9.3p194 :009 > q
 => #<Product id: 20, name: "iPad", description: "<p>\r\n\tiPad 11&quot; tablet that will change the way...", price: 499.0, vendor_id: 11, created_at: "2012-12-15 23:40:27", updated_at: "2013-01-01 00:18:39", image: "ipad.png", sku: "AB-09123"> 

q具有piggybak_sellable具有其他属性的属性。

1.9.3p194 :010 > q.piggybak_sellable
 => nil 

Product这是在 Rails Admin UI 中分配的可用属性的示例。

1.9.3p194 :011 > p.piggybak_sellable
 => #<Piggybak::Sellable id: 1, sku: "AR4590", description: "Blue Shirt", price: #<BigDecimal:7ffa1ba863b8,'0.2499E2',18(45)>, quantity: 100, item_id: 19, item_type: "Product", active: true, unlimited_inventory: false> 

我想将这些属性添加到nil记录中。

我想更新所有这些属性,q.piggybak_sellable而不必手动进行,即设置q.piggybak_sellable.sku = "ARJHR"等。

我试过做update_attributes,但没有奏效:

1.9.3p194 :008 > q.piggybak_sellable.update_attributes(:sku => "YJ4567", :description => "Awesome tablet", :price => 399, :quantity => 100, :item_id => 20, :item_type => "Product", :active => true)
NoMethodError: undefined method `update_attributes' for nil:NilClass

关于如何做到这一点的想法?

我试图把它放在我的Product模型上的回调中——为了它的价值。

谢谢。

4

3 回答 3

0

如果您收到的错误消息指出对象已经存在,则更新属性起作用。尝试这样的事情:

1.9.3p194 :008 > q.piggybak_sellable.create(:sku => "YJ4567", :description => "Awesome tablet", :price => 399, :quantity => 100, :item_id => 20, :item_type => "Product", :active => true)
于 2013-01-25T07:25:40.800 回答
0

正如marcamillion 已经说过的,您的协会显然不存在,至少在某些情况下是这样。现在的问题是如何让它静默初始化,以便在关联不存在时它不会中断。我会尝试像这样实现它:

( q.piggybak_sellable || q.build_piggyback_sellable ).
update_attributes(:sku => "YJ4567", :description => "Awesome tablet", 
                  :price => 399, :quantity => 100, :item_id => 20, 
                  :item_type => "Product", :active => true)
于 2013-01-25T08:51:24.580 回答
0

所以看来我需要做的是设置piggybak_sellable我的产品的属性,等于Piggybak::Sellable可以这样做的类的实例:

1.9.3p194 :006 > m.piggybak_sellable = Piggybak::Sellable.new({:sku => "YJ4567", :description => "Awesome tablet", :price => 399, :quantity => 50, :item_id => 20, :item_type => "Product", :active => true})
   (0.3ms)  begin transaction
  Piggybak::Sellable Exists (18.7ms)  SELECT 1 AS one FROM "sellables" WHERE "sellables"."sku" = 'YJ4567' LIMIT 1
  SQL (29.6ms)  INSERT INTO "sellables" ("active", "description", "item_id", "item_type", "price", "quantity", "sku", "unlimited_inventory") VALUES (?, ?, ?, ?, ?, ?, ?, ?)  [["active", true], ["description", "Awesome tablet"], ["item_id", 20], ["item_type", "Product"], ["price", #<BigDecimal:7fa97c8f29d8,'0.399E3',9(36)>], ["quantity", 50], ["sku", "YJ4567"], ["unlimited_inventory", false]]
   (2.7ms)  commit transaction
 => #<Piggybak::Sellable id: 3, sku: "YJ4567", description: "Awesome tablet", price: #<BigDecimal:7fa97cf2ec98,'0.399E3',9(36)>, quantity: 50, item_id: 20, item_type: "Product", active: true, unlimited_inventory: false> 
于 2013-01-25T18:11:19.957 回答