验证依赖于其他模型的活动记录的模型值?

发布于 2024-11-10 01:10:59 字数 511 浏览 0 评论 0原文

我有两个模型:

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等情况下工作。我已经尝试了上述方法,以及使用观察者,但它很脆弱。关于不同架构方法的建议也受到赞赏。

谢谢, 贾斯汀

I have two models:

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

and..

class Weight < ActiveRecord::Base
  belongs_to :category
  attr_accessible :value
end

I want to reliably set value to be (1/number of categories). I'd like this to work in the case of category.build_weight, category.new, category.create etc. I've tried the above approach, as well as using an observer, but its brittle. Suggestions on different architectural approaches also appreciated.

Thanks,
Justin

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清醇 2024-11-17 01:10:59

我会将创建逻辑从 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])

I would extract the creation logic out of the ActiveRecord model and into another class. Something like:

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])
小红帽 2024-11-17 01:10:59

为什么不使用验证前回调来设置权重,并验证模型中的权重? (如果你这样做,请确保考虑竞争条件......)

Why not use a before validation callback to set the weight, and validate the weight in the model? (If you do that, make sure you take race conditions into consideration...)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文