如何更新AR模型上属性的属性?

我正在使用piggybakgem 。

我有一个产品q

 1.9.3p194 :009 > q => #<Product id: 20, name: "iPad", description: "

\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管理UI中分配的Product可用属性的示例。

 1.9.3p194 :011 > p.piggybak_sellable => #<Piggybak::Sellable id: 1, sku: "AR4590", description: "Blue Shirt", price: #, 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模型的回调中 – 这是值得的。

谢谢。

如果对象已存在(如收到的错误消息所指示),则更新属性有效。 尝试这样的事情:

 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) 

因此,我需要做的是将我的产品的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", #], ["quantity", 50], ["sku", "YJ4567"], ["unlimited_inventory", false]] (2.7ms) commit transaction => #, quantity: 50, item_id: 20, item_type: "Product", active: true, unlimited_inventory: false> 

正如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)