2011-02-24 100 views
0

我有一個模塊:奇怪零對象結果

module Voteable 
    def has_up_vote_of user 
    return ! self.votes.select{|v| v.user.id == user.id && v.value == 1}.empty? 
    end 
    def has_down_vote_of user 
    return ! self.votes.select{|v| v.user.id == user.id && v.value == -1}.empty? 
    end 
end 

其被混合到一個模型:

class Comment < ActiveRecord::Base 
    include Voteable 
end 

在控制器代碼,有一個檢查:

has_up_vote = @voteable.has_up_vote_of @user 
has_down_vote = @voteable.has_down_vote_of @user 

@voteable和@user是現有模型項目,可在數據庫中找到。

假設,可供投票的項目有用戶的贊成票。在執行代碼之後,has_up_vote將等於true,並且has_down_vote將爲零

爲什麼零,而不是假?

我已經使用了幾種方法的變體,但問題是一樣的。即使這給了我同樣的效果:

def has_up_vote_of user 
    has = self.votes.select{|v| v.user.id == user.id && v.value == 1}.empty? 
    return !has.nil? && has 
end 

Posssible,我誤解的東西,但這種行爲很奇怪

更新

我發現很奇怪的行爲。

當我改變方法簡單:

def has_up_vote_of user 
    return false 
end 
def has_down_vote_of user 
    return false 
end 

他們都返回nil,當我調試應用程序。 但是,從控制檯,他們返回false。

這更爲直觀,因爲我對這些結果無能爲力。這些代碼是不工作:

has_up_vote = false if has_up_vote.nil? 
has_down_vote = false if has_down_vote.nil? 
+0

你得到的'self.votes.map {什麼| V | [v.user.id,v.value]}'? – 2011-02-24 13:21:56

+0

我得到相同的結果(has_down_vote爲零) – AntonAL 2011-02-24 13:30:19

+0

我要求你把'puts'語句,而不是替代'select'。 – 2011-02-24 13:32:07

回答

1

我認爲你在運行調試環境與的has_down_votes實際值干擾。按照定義,select方法不應該返回nil

0

我知道這並沒有得到你的奇怪問題的根源,但它應該給你你想要的結果。取而代之的

return ! self.votes.select{|v| v.user.id == user.id && v.value == -1}.empty? 

嘗試

return !!self.votes.select{|v| v.user.id == user.id && v.value == -1}.any? 

雙感嘆號是故意的 - 這將導致零變成假的。 (!arr.empty?相當於arr.any?相當於!! arr.any? - 除了最後一個將nil轉換爲false)

1

而不是!{}。empty?你可以使用{} .present?

它的可讀性更強,輸出將永遠是真/假只有