我在 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
.