Rails - Why is my custom validation being triggered for only a build command.
- by adam
I have a sentence and correction model with a has_one and belongs_to relationship respectively.
For some reason when I do
def create
@sentence = Sentence.find(params[:sentence_id])
@correction = @sentence.build_correction(params[:correction])
a custom validation I wrote for Correction is being called at the build_correction point. the validation is below
class Correction < ActiveRecord::Base
attr_accessible :text, :sentence_id, :user_id
belongs_to :sentence
belongs_to :user
validate :correction_is_different_than_sentence
def correction_is_different_than_sentence
errors.add(:text, "can't be the same as the original sentence.") if (text == self.sentence.text)
end
the problem is for some reason on validation the correction object doesn't have the sentence id set (despite I used the build_correction method) and so it complains
"you have nil object .... while executing nil.text" in the if clause in the validation above.
So my question is why is the validation occuring for a build command, i thought it only triggers on a create or update. And why isnt the sentence_id getting set?