3

Railsアプリのページで3つの変数を定義しています。

  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上記のものと等しい3つの変数宣言を記述して、変数が常にの代わりになるようにするにはどうすればよいですか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 に答える