2010-01-17 66 views
1

奇怪的是,我的模型通過驗證蠻好的,作爲預期,但我仍然有渲染到視圖中的錯誤。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} 

而且即使它是成功的,這是連續地返回。

想法如何調試呢?

回答

0

它看起來並不像它經過驗證,因爲成功狀態是假的。

如果你看看你自定義的驗證看來,「除非」關鍵字引起了一些混亂。

嘗試:

if !last_vote_cast_by_voter.nil? && last_vote_cast_by_voter.created_at < 5.seconds.ago 
    errors.add_to_base ... 
+0

看來你是對的。但是這並沒有解決它。否則,我的驗證有任何問題嗎? – 2010-01-17 06:54:29

0

我覺得你unless說法是錯誤的。我個人不習慣他們,所以我總是改寫爲if語句

if last_vote_cast_by_voter.nil? == false && last_vote_cast_by_voter.created_at > 5.seconds.ago 

看着這條線,我會懷疑last_vote_cast_by_voter.created_at應低於5秒,所以我想你的,除非聲明應改爲

unless last_vote_cast_by_voter.nil? || last_vote_cast_by_voter.created_at > 5.seconds.ago 

添加@vote.errors.clear的確沒有幫助,因爲認爲在已經點呈現...

如果,你投一些票,這仍然是行不通的嘗試寫一個測試。例如,兩票之間的時間應該是1秒和10秒。
檢查Vote.find_last_by_voter_id是否正常工作。

如果所有這些測試都工作,並且使你的觀點是沒有,那麼一些奇怪的事情在你的觀點怎麼回事,你應該張貼關於您的視圖更多信息,我猜。

1

的問題是完全離奇,並與render => :json。奇怪的是:success密鑰不能在哈希中,當respond_to塊呈現json。

這是要改變的是唯一需要的變化:

format.js { render :json => {:model => 'vote', :errors => @vote.errors.on_base, :success => @vote.errors.on_base.nil?} } 

而且我記錄與導軌團隊票。