这有什么问题before_save-callback
?
class Order < ActiveRecord::Base
has_many :line_items, :dependent => :destroy, :inverse_of => :order
accepts_nested_attributes_for :line_items
attr_accessible :line_items_attributes
before_save :mark_line_items_for_removal
def mark_line_items_for_removal
line_items.each do |line_item|
line_item.mark_for_destruction if line_item.quantity.to_f <= 0
end
end
end
Run Code Online (Sandbox Code Playgroud)
当其中之一line_items
被标记为销毁时,line_item
将不会保存。然而,父 Order 对象确实得到了保存。返回 true 并没有什么区别......
关于 mark_for_destruction:http ://apidock.com/rails/v3.1.0/ActiveRecord/AutosaveAssociation/mark_for_destruction 以及为什么不是“:allow_destroy => true”?见这里:http : //weblogs.manas.com.ar/spalladino/2010/03/15/deleting-children-with-accepts_nested_attributes_for-in-rails/
如果评估为false,Javascript中是否有一些速记来分配变量?
在红宝石中,我可以这样做:
foo |= "bar"
Run Code Online (Sandbox Code Playgroud)
如果foo的计算结果为false,则将"bar"分配给foo,如下所示:(使用该| =运算符)
var cars_by_brand_and_color = {};
for (var car in parking_lot) {
// add a brand if it doesn't exist yet;
// cars_by_brand_and_color['chevrolet'] = {};
cars_by_brand_and_color[car['brand']] |= {};
// and add that color to the brand if it doesn't exist yet;
// cars_by_brand_and_color['chevrolet']['grey'] |= {};
cars_by_brand_and_color[car['brand']][car['color']] |= {};
// now let's add that car;
// cars_by_brand_and_color['chevrolet']['grey']['BDB-565'] = 'Mr. Smith';
cars_by_brand_and_color[car['brand']][car['color']][car['lisence_plate']] = car['owner']
};
Run Code Online (Sandbox Code Playgroud)