如何解决验证活动记录的模型值是否取决于其他模型?
| 我有两个模型:class Category < ActiveRecord::Base
has_one :weight
after_create :create_category_weight
def create_category_weight
self.weight = Weight.new :value => 1/Category.count
end
end
和..
class Weight < ActiveRecord::Base
belongs_to :category
attr_accessible :value
end
我想可靠地将值设置为(1 /类别数)。我希望在category.build_weight,category.new,category.create等情况下可以使用此方法。对不同的架构方法的建议也表示赞赏。
谢谢,
贾斯汀
解决方法
我将从ActiveRecord模型中提取创建逻辑并提取到另一个类中。就像是:
class CategoryRepository
def new_category
@category = Category.new
@category.weight = Weight.new(:value => (1 / Category.count))
@category
end
def create_category(attributes)
@category = Category.create(attributes)
@category.weight = Weight.new(:value => (1 / Category.count))
@category.save
@category
end
end
@repository = CategoryRepository.new
@category = @repository.new_category
@category = @repository.create_category(params[:category])
,为什么不使用验证前回调来设置权重并在模型中验证权重? (如果这样做,请确保考虑到比赛条件...)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。