我需要運行SQL查詢像Rails的SQL查詢生成器......還是ActiveRecord的查詢生成器
sql = 'SELECT * FROM users WHERE id != ' + self.id.to_s + ' AND id NOT IN (SELECT artner_id FROM encounters WHERE user_id = ' + self.id.to_s + ')'
sql += ' AND id NOT IN (SELECT user_id FROM encounters WHERE partner_id = ' + self.id.to_s + ' AND predisposition = ' + Encounter::Negative.to_s + ')'
sql += ' AND cfg_sex = ' + self.sex.to_s + ' AND cfg_country = ' + self.country.to_s + ' AND cfg_city = ' + self.city.to_s
sql += ' ORDER BY rand() LIMIT 1'
它可以通過AR.find_by_sql執行,但之前的代碼是壞的可讀性。 是否有任何查詢生成器可以構建該查詢?
例如,Kohana的(這是PHP框架,我PHP開發人員,但我想改變孩子的語言來的Ruby/Rails)有一個查詢生成器,它的工作原理是這樣的:
$sql = DB::select('*')->from('users');
$sql->where('id', 'NOT_IN', DB::expr('SELECT partner_id FROM encounters WHERE user_id = '.$user->id));
$sql->where('id', 'NOT_IN', DB::expr('SELECT user_id FROM encounters WHERE partner_id = '.$user->id.' AND predisposition = '.Encounter::Negative));
....
etc
...
使用查詢生成器(如Kohana查詢生成器)構建的查詢更具可讀性和可理解性。
有沒有什麼寶石可以解決這個問題?
它可以粘貼分貝表達式查詢,來樣訂做查詢開頭的部分「SELECT * FROM用戶WHERE ID !='+ self.id.to_s +'AND ID NOT IN(SELECT artner_id FROM encounters WHERE user_id ='+ self.id.to_s +')'? –
@Zhirayr我編輯了答案 – gmile
爲什麼不在這種情況下進行左連接? –