2014-10-22 26 views
0

我有一段代碼可以提取我關注的用戶的id列表。需要將數組轉換爲Integer以在Rails API中進行MySQL查詢

@followed = current_user.followed_user_ids

它給了我這樣的[11,3,24,42]

我需要把這些東西加到不能在MySQL中查詢的結果。 目前,我得到NOT IN ([11,3,24,42])這是一個錯誤。我需要NOT IN (11,3,24,42)

這是find_by_sql聲明的一部分,所以在這一點上我不可能使用where.not

回答

3

在軌道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語句,並提供任何結果(這可能是在方案中預期的情況)。

+0

謝謝。但是,查詢的其餘部分是使用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

+0

然後使用'@ followed.join(「,」)'。如果@followed是一個空白數組,可能會給您帶來問題。爲了解決這個問題,你可以寫'NOT IN(0#{@ followed.join(',')})',如果數組爲空,就會產生'NOT IN(0)'。 – Fer 2014-10-22 08:23:13

+0

@lokesh請將這些細節添加到您的問題。 – Stefan 2014-10-22 08:30:21

1

,你可以這樣做:

@followed = [11,3,24,42] 
User.where('id not in (?)', @followed) 
+0

謝謝。但是,查詢的其餘部分是使用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;「)。我如何在這裏使用你的代碼?可能使用'User.joins('INNER JOIN ...'),其中('...')。group('')可能爲 – lokesh 2014-10-22 08:19:49

+0

。限制(30).order('order_index DESC')'。也許你應該看看[教程](http://guides.rubyonrails.org/active_record_querying.html),並嘗試找出最適合你的東西 – 2014-10-22 08:34:06