我需要像这样运行 sql 查询
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 查询构建器等查询构建器构建的查询更具可读性和可理解性。
有什么宝石可以解决这个问题吗?