snippets-rails

rails中数据库事务:
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


在ActionRecord的count()上添加适当的条件

blog.posts.count(:conditions => "status = 'active'")


选择特定列的数据
class User < ActiveRecord::Base
  def self.names
    # find all records, then map name attributes to an array
    find(:all, :select => "name").map(&:name)
  end
end


around_filter 环绕过滤器
class AssetController < ActionController

  around_filter (:only => :assets) do |controller,action_block| 
    controller.benchmark("Benchmarking...") { action_block.call }
  end
  ...
end

你可能感兴趣的:(sql,Blog,Rails,ActiveRecord)