2012-04-06 57 views
4

我有投票和投票表格的投票。我可以在投票和投票模式中驗證唯一性,以確保用戶不能投票或投票超過一次。我想驗證這兩種模式的獨特性,以便用戶不會投票選出他們已經投票過的帖子,反之亦然。我試過了下面定義的自定義驗證,userfaved,但它不起作用。Rails - 驗證基於另一個表的唯一性

class Vote < ActiveRecord::Base 

validates_uniqueness_of :user_id, :scope => :article_id #allows only one vote 

validate :userfaved 

def userfaved 
    if Votedown.where(:user_id => :user_id, :artcle_id => :article_id).any? 
     errors.add(:user_id, 'already voted on this') 
    end 
end 



class Votedown < ActiveRecord::Base 

validates_uniqueness_of :user_id, :scope => :article_id #allows only one votedown 

validate :userfaved 

def userfaved 
    if Vote.where(:user_id=> :user_id, :article_id => :article_id).any? 
     errors.add(:user_id, 'already voted on this') 
    end 
end 
+0

我知道這已經有一段時間了,因爲你問了這個問題,但我想知道爲什麼你不只是使用一張表代表投票類型的列(上或下)?這將消除您對複雜驗證的需求。你只需要像你已經完成的那樣驗證':user_id,:scope =>:article_id'的唯一性。 – 2013-08-30 02:15:36

回答

2

它看起來像有在你驗證了一個錯誤:在哈希你傳遞給where值是符號。它更改爲以下,它應該工作:

Votedown.where(:user_id => self.user_id, :article_id => self.article_id).any? 

但我認爲有一個簡單的方法來做到這一點。你可以只有一個表Votes並添加一個屬性,記錄它是否是向上或向下?這會讓你的獨特性檢查變得非常簡單。如果你真的想爲它分開類,你可以使用單表繼承:有一個votes表,一個超類Vote,和兩個子類VoteUpVoteDown

+0

是否有可能從另一個模型中提取數據(即在Vote模型中運行Votedown上的where過濾器)? – 2012-04-07 01:50:27

+0

如果您使用我建議的層次結構,則VoteUp.where(...)將查找VoteUp條目,VoteDown.where(...)將查找VoteDown條目,並且Vote.where(...)將查找這兩個條目。有關單表繼承的更多信息,請訪問:http://juixe.com/techknow/index.php/2006/06/03/rails-single-table-inheritance/ – tsherif 2012-04-07 04:58:04

+0

感謝您的評論;它的幫助,但我會試圖讓我有工作,可能通過控制器。 – 2012-04-07 13:24:02