我在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
。
答案 0 :(得分:2)
您可以在此处使用条件赋值运算符来帮助减少代码。例如:
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
upvotes = Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 0).count[post.id] || 0
downvotes = Vote.group(:post_id).where(:post_id => @posts.map(&:id), :direction => 1).count[post.id] || 0
条件赋值运算符实质上表示如果第一部分的计算结果为nil,则使用右侧作为默认值。