我正在使用the piggybak gem。
我有一个产品q
:
1.9.3p194 :009 > q
=> #<Product id: 20, name: "iPad", description: "<p>\r\n\tiPad 11" 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
这是已在Rails管理界面中分配的Product
可用属性的示例。
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
模型的回调中 - 这是值得的。
感谢。
答案 0 :(得分: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)
答案 1 :(得分: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)
答案 2 :(得分: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>