我有一個分別具有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?
我認爲它會工作,如果你註釋掉「attr_accessible:text,:sentence_id,:user_id」 – Salil 2010-04-27 11:30:22
感謝您的答覆。不幸的是它沒有改變任何東西 – robodisco 2010-04-27 12:06:39