views:

46

answers:

1

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?

A: 

As ever it was not rails fault but my own - its trivial, long to explain, no use to anyone else so wont explain.

adam