3

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

4

1 回答 1

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,则使用右侧作为默认值。

于 2013-01-11T03:44:05.863 回答