在rails中查询为表

时间:2017-03-03 03:31:06

标签: ruby-on-rails

大家好我需要一些帮助,你如何在rails控制器中创建这个查询?

SELECT * FROM(SELECT id,amount,user_id FROM payments 在哪里user_id =' 10000' ORDER BY id DESC)WHERE rownum< = 1;

2 个答案:

答案 0 :(得分:3)

这是在rails中的方式

Payment.select('*').from(Payment.select('id,amount,user_id, row_number over () as rn').where("user_id= 10000").order('id DESC')).where('rn <= 1')

OR

Payment.find_by_sql('SELECT * FROM (SELECT id,amount,user_id FROM payments WHERE user_id='10000' ORDER BY id DESC) WHERE rownum <=1')

答案 1 :(得分:1)

试试这个:

sql = "SELECT * FROM (SELECT id,amount,user_id FROM payments WHERE user_id='10000' ORDER BY id DESC) WHERE rownum <=1;"

ActiveRecord::Base.connection.execute(sql)