User Helper Method - grabbing users whose ID doesn't match current user ID

98 views Asked by At

trying to write a helper method with 3 basic conditions. adding the 3rd one, which is trying to take the current user out of the results, is resulting in an error.

  def male_soccer_players
    return User.where(:gender => "male", :soccer => true, :id != current_user.id)
  end

The error is

app/controllers/application_controller.rb:12: syntax error, unexpected ')', expecting => 
3

There are 3 answers

0
Roman Kiselenko On BEST ANSWER

Problem in this :id != current_user.id Rails .where pass only hash try

def male_soccer_players
  User.where(:gender => "male", :soccer => true).where('id != ?', current_user.id)
end

or

def male_soccer_players
  User.where('gender = ? and soccer = ? and id != ?', "male", true, current_user.id)
end
0
Pankhuri Kaushik On

Try this:

 def male_soccer_players
        return User.where(:gender => "male", :soccer => true).where("id not != ", current_user.id)
    end
1
Mohamad On

Why not create a scope?

scope :except, ->(user) { where.not(id: user) }

And in your case:

def male_soccer_players
  User.except(current_user).where(:gender => "male", :soccer => true)
end

Optionally, if you want, you can take this a step further and create other scopes if reusability is something that interests you:

scope :male, -> { where(gender: "male") }
scope :soccer_player, -> { where(soccer: true) }

def male_soccer_players
  User.male.soccer_player.except(current_user)
end