试图用3个基本条件编写辅助方法。添加第3个,试图将当前用户从结果中取出,会导致错误。
def male_soccer_players
return User.where(:gender => "male", :soccer => true, :id != current_user.id)
end
错误是
app/controllers/application_controller.rb:12: syntax error, unexpected ')', expecting =>
答案 0 :(得分:1)
此问题:id != current_user.id
Rails .where
仅传递哈希值
试试
def male_soccer_players
User.where(:gender => "male", :soccer => true).where('id != ?', current_user.id)
end
或
def male_soccer_players
User.where('gender = ? and soccer = ? and id != ?', "male", true, current_user.id)
end
答案 1 :(得分:1)
为什么不创建范围?
scope :except, ->(user) { where.not(id: user) }
在你的情况下:
def male_soccer_players
User.except(current_user).where(:gender => "male", :soccer => true)
end
可选如果您想要,您可以更进一步,如果可重用性是您感兴趣的话,可以创建其他范围:
scope :male, -> { where(gender: "male") }
scope :soccer_player, -> { where(soccer: true) }
def male_soccer_players
User.male.soccer_player.except(current_user)
end
答案 2 :(得分:0)
试试这个:
def male_soccer_players
return User.where(:gender => "male", :soccer => true).where("id not != ", current_user.id)
end