class Variant
validate :check_price
# Ensures a new variant takes the product master price when price is not supplied
def check_price
if price.nil? && Config[:require_master_price]
raise 'No master variant found to infer price' unless (product && product.master)
raise 'Must supply price for variant or master.price for product.' if self == product.master
self.price = product.master.price
end
if currency.nil?
self.currency = Config[:currency]
end
end
class LineItem
belongs_to :variant, inverse_of: :line_items
before_validation :copy_price
def copy_price
if variant
update_price if price.nil?
self.cost_price = variant.cost_price if cost_price.nil?
self.currency = variant.currency if currency.nil?
end
end
variant 数据库列中没有 currency 列
+----+-----------+--------+--------+-------+-------+------------+-----------+------------+------------+------------+----------+-------------+------------+-------------+------------+
| id | sku | weight | height | width | depth | deleted_at | is_master | product_id | cost_price | cost_cu... | position | track_in... | tax_cat... | updated_at | stock_i... |
+----+-----------+--------+--------+-------+-------+------------+-----------+------------+------------+------------+----------+-------------+------------+-------------+------------+
| 1 | R00011 | 0.0 | | | | | true | 1 | 17.0 | USD | 2 | true | | 2015-07-... | 1 |
+----+-----------+--------+--------+-------+-------+------------+-----------+------------+------------+------------+----------+-------------+------------+-------------+------------+
1 row in set
以下方法会做数据验证,如果验证失败就不会把对象存入数据库: create create! save save! update update!
问题:variant 数据库列中没有 currency 列,所以不能持久化,但是 LineItem 中能使用 variant.currency,难道每次 variant 数据出库会执行 validate :check_price 吗? validate :check_price 在数据创建和读取都会调用吗?read 方法也会执行数据验证吗?