2016年8月9日 星期二

Rails直接執行SQL command

雖然Rails的ActiveRecord API相當好用,但是真的遇到要對大批資料異動,而且還附帶複雜的Join邏輯時,要想用ActiveRecord來兜出需要的語法就會相當頭痛,相對的也就是簡單的一段SQL command就解決的事,處理起來的performance還比較高,這時也是可以讓Rails直接執行SQL command,只要使用

sql = "update customers as c inner join customers as c1 on c.introduce_id = c1.orig_cust_id set c.referral_cust_id = c1.id where c.introduce_id is not null"
ActiveRecord::Base.connection.execute(sql)
#也可以搭配一個變數來接收回傳值
results = ActiveRecord::Base.connection.execute(sql)

沒有留言: