我有下表和相应的模型:
Orders
ID|ORDER_REF|....
订单参考的格式为'ORDER#000-00'+ORDER.ID 问题是我需要启用它,以便在插入时设置订单参考。有没有办法做到这一点而无需在插入后进行更新,我在这里使用 RoR。
我有下表和相应的模型:
Orders
ID|ORDER_REF|....
订单参考的格式为'ORDER#000-00'+ORDER.ID 问题是我需要启用它,以便在插入时设置订单参考。有没有办法做到这一点而无需在插入后进行更新,我在这里使用 RoR。
Do you really need that data in your database? The best way would be to just have a method on your model that returns the order ref in the desired format, based on the id
in the database.
class Order < ActiveRecord::Base
def order_ref
"ORDER#000-#{self.id.to_s.rjust(3, '0')}"
end
end
With the abobe you can do this:
order = Order.create(params[:order])
order.id #=> 12
order.order_ref #=> "ORDER#000-012"
If you do need the order ref in the database, I recommend using an after_create
callback:
class Order < ActiveRecord::Base
after_create :generate_order_ref
def generate_order_ref
self.order_ref = "ORDER#000-#{self.id.to_s.rjust(3, '0')}"
save
end
end
This does do an update after inserting, but I don't see any problem with that.