I have a complex model relationship hierarchy setup, Here are the relevant parts ( Channel and ChannelTagWeight model) as:
class Channel
include Mongoid::Document
embeds_many :channel_tag_weights
def sum_of_channel_tag_weights
sum = 0
self.channel_tag_weights.each { |ctw| sum = sum + ctw.weight }
errors.add(:channel_tag_weight,"sum for all MasterTags should equal 10") unless sum == 10
end
end
I have ChannelTagWeights
as
class ChannelTagWeight
include Mongoid::Document
embedded_in :channel
field :weight, type: Integer
belongs_to :mastertag
validates :weight, :presence => true
end
I have my Factory setup for Channel as:
factory :playtex_website, :class => Channel do
url 'http://www.playtexplayon.com/'
after(:build) do |channel|
channel.channel_tag_weights << FactoryGirl.create(:playtex_tag_weight,channel: channel)
channel.channel_tag_weights << FactoryGirl.create(:playtex_tag_weight2,channel: channel)
end
end
For ChannelTagWeights :
factory :playtex_tag_weight, :class => ChannelTagWeight do
weight 8
after(:build) do |channel_tag_weight|
channel_tag_weight.mastertag = channel_tag_weight.channel.company.project.mastertags.first
end
end
factory :playtex_tag_weight2, :class => ChannelTagWeight do
weight 2
after(:build) do |channel_tag_weight|
channel_tag_weight.mastertag = channel_tag_weight.channel.company.project.mastertags.last
end
end
I always end up with :
Mongoid::Errors::Validations:
Problem:
Validation of Website failed.
Summary:
The following errors were found: Channel tag weight sum for all MasterTags should equal 10
Resolution:
Try persisting the document with valid data or remove the validations.
Where am I going wrong? How to solve this issue?