在軌道4,5:
@followed = current_user.followed_user_ids # @followed = [11,3,24,42]
@not_followed = User.where.not(id: @followed)
這應該產生類似select * from users where id not in (11,3,24,42)
當你評論,你正在使用find_by_slq
(在所有軌道版本可用)。然後,你可以使用join
方法:
query = "select * from users where id not in (#{@followed.join(',')})"
這將提高MySQL的錯誤,如果@followed
是空白的,生成的查詢將
select * from users where id not in()
爲了解決這個whiout specifiying aditional的if語句的代碼,您可以使用:
query = "select * from users where id not in (0#{@followed.join(',')})"
你的正常查詢會是這樣:
select * from users where id not in (01,2,3,4)
但如果數組是空的,然後會導致
select * from users where id not in (0)
這是一個仍然有效的SQL語句,並提供任何結果(這可能是在方案中預期的情況)。
來源
2014-10-22 07:53:03
Fer
謝謝。但是,查詢的其餘部分是使用find_by_sql編寫的。它類似於 @people = User.find_by_sql(「Select .................... ON u.id = r.user_id WHERE u.id NOT IN ( #{@ followed})GROUP BY u.id ORDER BY order_index DESC LIMIT 30;「)。我如何在這裏使用你的代碼? – lokesh 2014-10-22 08:17:16
然後使用'@ followed.join(「,」)'。如果@followed是一個空白數組,可能會給您帶來問題。爲了解決這個問題,你可以寫'NOT IN(0#{@ followed.join(',')})',如果數組爲空,就會產生'NOT IN(0)'。 – Fer 2014-10-22 08:23:13
@lokesh請將這些細節添加到您的問題。 – Stefan 2014-10-22 08:30:21