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? SEL开发者_Python百科ECT 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
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.
精彩评论