在rails使用mysql語法

這個語法放在我的桌面上一直很久了,一直沒機會用,先貼些語法留著,以後會有機會用到!

code 1
[cc lang=”ruby”]
namespace :db do
desc “Cleanup the database by setting rows to deleted when older than xxx. Defaults to development database. Set RAILS_ENV=[production, test, etc.] to override.”
task :cleanup => :environment do
sql = “在這裡寫 sql 語法”
# used to connect active record to the database
ActiveRecord::Base.establish_connection
ActiveRecord::Base.connection.execute(sql)
end
end
[/cc]

code 2
[cc lang=”ruby”]
def fetch_value
sql = ActiveRecord::Base.connection();
sql.execute “SET autocommit=0”;
sql.begin_db_transaction
id, value =
sql.execute(“SELECT id, value FROM sometable WHERE used=0 LIMIT 1 FOR UPDATE”).fetch_row;
sql.update “UPDATE sometable SET used=1 WHERE id=#{id}”;
sql.commit_db_transaction

value;
end[/cc]

這個用法可以用自己的查詢方法來撈資料,但,不建議使用來 alter 資料表,因為會對版本更動會有很不好的狀況。

詳情請看這裡:http://www.anyexample.com/webdev/rails/rails_and_sql_queries.xml