2010-04-27 25 views
1

我有一個分別具有has_one和belongs_to關係的句子和校正模型。Rails - 爲什麼我的自定義驗證僅針對構建命令觸發

出於某種原因,當我做

def create 

     @sentence = Sentence.find(params[:sentence_id]) 
     @correction = @sentence.build_correction(params[:correction]) 

我寫了修正定義驗證被稱爲在build_correction點。驗證低於

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 

問題是由於某種原因在驗證修正對象沒有一句ID集(儘管我用build_correction方法),並因此抱怨 「你有對象爲零.. ..在執行上面的驗證中的if子句中的nil.text時。

所以我的問題是爲什麼驗證發生的構建命令,我認爲它只觸發創建或更新。爲什麼沒有設置sentence_id?

+0

我認爲它會工作,如果你註釋掉「attr_accessible:text,:sentence_id,:user_id」 – Salil 2010-04-27 11:30:22

+0

感謝您的答覆。不幸的是它沒有改變任何東西 – robodisco 2010-04-27 12:06:39

回答

-3

儘管它不是鋼軌故障,但我自己 - 它的微不足道的,很長的解釋,沒有用於任何人,所以不會解釋。

0

有些錯誤給我造成了很多麻煩。不知道爲什麼,但將自定義驗證器調用移動到其他驗證器調用的最後,爲我解決了這個問題。

以前

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/ 

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 

這裏是我的自定義驗證

private 

def uniq_name 
    return if clone? 
    user_product = self.user.products.unlocked.where(:name => self.name).first 
    errors[:name] << "has already been taken" if user_product && !user_product.id.eql?(self.id) 
end 

試試這個,可能是它會做的伎倆對你太。