【发布时间】:2011-02-24 12:57:22
【问题描述】:
我有一个模块:
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 将为 nil。
为什么是 nil,而不是 false ?
我使用了几种不同的方法,但问题是一样的。即使这样也给了我同样的效果:
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
可能,我误解了一些东西,但这种行为很奇怪
更新
我注意到非常奇怪的行为。
当我将方法更改为微不足道时:
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?
【问题讨论】:
-
self.votes.map { |v| [v.user.id, v.value] }能得到什么? -
我得到相同的结果(has_down_vote 为 nil)
-
我请你
puts那个声明,而不是用它代替select。 -
这很奇怪,我正在尝试用:
ruby-1.8.7-p302 > def test2; return ! [User.last, User.first].select {|u| u.id == 10000 && 1 == -1 }.empty?; end => nil ruby-1.8.7-p302 > test2 => false复制它,这应该是相同的,这确实让我返回 false 并且永远不会为零。您是否在控制台中尝试这些测试?如果您将该行粘贴到控制台中,您会得到什么:(! Comment.last.votes.select{|v| v.user.id == user.id && v.value == -1}.empty?) -
@John Feminella,它返回一个数组对 [v.user_id, v.value]
标签: ruby-on-rails ruby