非常棘手的 Rails 验证问题

发布于 2024-11-17 10:57:48 字数 600 浏览 0 评论 0原文

我在这里遇到了一个非常棘手的验证问题。所以基本上,我有一个连接模型 screen_weights 和一个名为“weight”的额外属性。连接模型有两种模型:分数和屏幕。

Screen has_many :scores through=>:screen_weights

Score has_many :screens through=>:screen_weights

然后根据权重对我的分数进行加权。

假设我有

screen_id=1,score_id=1,weight=0.3;

screen_id=1,score_id=2,weight=0.7.

这样,我就会有一些东西如屏幕 1 所示,它有两个分数(1 和 2),权重分别为 0.3 和 0.7。需要进行的验证是总和为 1。 如果分数权重加起来为 1,我将需要检查特定屏幕。我将如何实现这一目标? SELECT SUM(weight) FROM screen_weights GROUP BY screen_id 可以给我这个信息。但我该如何为其编写验证呢? 多谢

I am having a very tricky problem here with validation. So basically, I have a join model screen_weights with an extra attribute called "weight". The join model is for two models:score and screen.

Screen has_many :scores through=>:screen_weights

Score has_many :screens through=>:screen_weights

and then my scores are weighed depending on the weight.

let's say I have

screen_id=1,score_id=1,weight=0.3;

screen_id=1,score_id=2,weight=0.7.

In this way, I will have something as screen 1 which has two scores (1 and 2) with weights 0.3 and 0.7 respectively. The validation needs to be done is sum to 1.
I will need to check for a particular screen if the weights for the scores add up to 1. How would I achieve this? SELECT SUM(weight) FROM screen_weights GROUP BY screen_id can give me this information. But how can I write a validation for it?
Thanks a lot

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

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

发布评论

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

评论(1

忘羡 2024-11-24 10:57:48
class Screen
  has_many :screen_weights
  validate :weights_sum_to_1

  def weights_sum_to_1
    errors.add_to_base("Weights must add up to 1") unless screen_weights.sum(:weight) == 1
  end
end

我认为这就是您想要的,尽管从您对问题的解释中很难准确说出这些类在做什么。

class Screen
  has_many :screen_weights
  validate :weights_sum_to_1

  def weights_sum_to_1
    errors.add_to_base("Weights must add up to 1") unless screen_weights.sum(:weight) == 1
  end
end

I think this is what you're going for, though from your explanation of the problem its hard to tell exactly what the classes are doing.

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