Rails - Why is my custom validation being triggered for only a build command -
i have sentence , correction model has_one , belongs_to relationship respectively.
for reason when do
def create @sentence = sentence.find(params[:sentence_id]) @correction = @sentence.build_correction(params[:correction])
a custom validation wrote correction being called @ build_correction point. validation 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 same original sentence.") if (text == self.sentence.text) end
the problem reason on validation correction object doesn't have sentence id set (despite used build_correction method) , complains "you have nil object .... while executing nil.text" in if clause in validation above.
so question why validation occuring build command, thought triggers on create or update. , why isnt sentence_id getting set?
some error creating lot of headaches me. don't know why moving custom validator call end of other validator calls fixed me.
before
validates :name, :short_description, presence: true validate :uniq_name validates :price, :numericality => {:greater_than_or_equal_to => 0} validates_attachment_content_type :image, :content_type => /image/
after
validates :name, :short_description, presence: true validates :price, :numericality => {:greater_than_or_equal_to => 0} validates_attachment_content_type :image, :content_type => /image/ validate :uniq_name
here custom validator
private def uniq_name return if clone? user_product = self.user.products.unlocked.where(:name => self.name).first errors[:name] << "has been taken" if user_product && !user_product.id.eql?(self.id) end
try this, may trick too.
Comments
Post a Comment