我在Rails应用程序的页面上定义了三个变量:
if current_user
if Vote.where(:user_id => current_user.id, :post_id => post.id, :direction => 0).count > 0
active = ' upactive'
elsif Vote.where(:user_id => current_user.id, :post_id => post.id, :direction => 1).count > 0
active = ' downactive'
end
end
unless Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 0).count[post.id] == nil
upvotes = Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 0).count[post.id]
else
upvotes = 0
end
unless Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 1).count[post.id] == nil
downvotes = Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 1).count[post.id]
else
downvotes = 0
end
我注意到if和unless语句中有很多重复的代码。如何编写三个变量声明,使它们等于上面的变量声明,并确保变量始终为0
而不是nil
。
elseif
改为else
,因为如果两个Vote
查询的count == 0
,就有可能导致active
未定义,从而存在潜在的逻辑漏洞。 - the Tin Man