2013-10-29 79 views
0

我想寫Rails的這個查詢/ Active Record的ActiveRecord的查詢在其他查詢,如「中的」使用SQL

SELECT * FROM messages WHERE (realtor_id,created_at) IN (SELECT realtor_id, MAX(created_at),message FROM messages WHERE `messages`.`user_id` = 8 GROUP BY realtor_id); 

我嘗試了一些語法,但它不工作... 我認爲,解決辦法近:

@discussions = Message.where(realtor_id: created_at: [Message.where(:user_id => current_user.id).select("realtor_id, MAX(created_at) as created_at").group("realtor_id").order("created_at ASC")]) 

有人能幫助我嗎?

感謝提前,

F.

回答

1

您可以創建SQL查詢,並通過在

query = "SELECT * FROM messages WHERE (realtor_id,created_at) IN (SELECT realtor_id, MAX(created_at),message FROM messages WHERE `messages`.`user_id` = 8 GROUP BY realtor_id)" 

@discussions = ActiveRecord::Base.connection.execute(query)