先上代码:
class Micropost < ActiveRecord::Base
# 省略
has_many :post_food_relationships, foreign_key: :post_id, dependent: :destroy
has_many :foods, through: :post_food_relationships
include MicropostCreator
#省略
end
由于 Micropost 和 Food 是 多对多 的关系,新建一个有食物信息的 Micropost 时就需要写三个表:
这时需要把三者放入一个 transaction 中:
module MicropostCreator extend BasicCreator
transaction_around :save_with_foods
logging_before :save_with_foods
def save_with_foods(foods_parmas)
# save micropost, foods, post_food_relationships
end
end
我希望通过一个方法 transaction_around(*method_names) 来使方法在 transaction 中运行:
module BasicCreator
def transaction_around(*method_names)
method_names.each do |name|
m = instance_method(name)
define_method name do |*params|
transaction do
puts "transaction"
m.bind(self).call(*params)
end
end
end
end
def logging_before(*method_names)
method_names.each do |name|
m = instance_method(name)
define_method name do |*params|
puts "Running #{self.class}##{m.name}(#{params.inspect})"
m.bind(self).call(*params)
end
end
end
end
发现 transaction_around 必须放在方法声明之后,如何才能无视位置?