Rails - Why is my custom validation being triggered for only a build command.

Posted by adam on Stack Overflow See other posts from Stack Overflow or by adam
Published on 2010-04-27T11:17:58Z Indexed on 2010/04/27 11:23 UTC
Read the original article Hit count: 197

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about validation