奇怪的是,我的模型通過驗證蠻好的,作爲預期,但我仍然有渲染到視圖中的錯誤。Rails模型通過驗證但查看仍呈現錯誤?
# Controller
def up
@vote = Vote.create :vote => true, :voter => current_user, :voteable => Recipe.find(params[:id])
respond_to do |format|
format.js { render :json => {:model => 'vote', :success => @vote.valid?, :errors => @vote.errors }}
end
@vote.errors.clear # <= doesn't seem to help
end
我寫的模型有一個自定義的驗證:
class Vote < ActiveRecord::Base
# ... associations etc.
validate :voter_voting_too_frequently?
private
def voter_voting_too_frequently?
last_vote_cast_by_voter = Vote.find_last_by_voter_id self.voter
unless last_vote_cast_by_voter.nil? || last_vote_cast_by_voter.created_at < 5.seconds.ago
errors.add_to_base("You can only vote every 5 seconds.")
end
end
end
最後,被渲染到視圖的響應:(返回爲JS毫無疑問,但將是相同的,如果它是在<div>
)
{"errors":[["base","You can only vote every 5 seconds."]],"model":"vote","success":false}
而且即使它是成功的,這是連續地返回。
想法如何調試呢?
看來你是對的。但是這並沒有解決它。否則,我的驗證有任何問題嗎? – 2010-01-17 06:54:29