Notes posted by leente
RSS feedSee also: sample
sample randomly picks 1 or n elements from the array
Without module
If you want to have only the path prefix without namespacing your controller, pass :module => false.
Normal:
namespace :account do resources :transactions, :only => [:index] end account_transactions GET /account/transactions(.:format) {:controller=>"account/transactions", :action=>"index"}
With :module => false:
namespace :account, :module => false do resources :transactions, :only => [:index] end account_transactions GET /account/transactions(.:format) {:controller=>"transactions", :action=>"index"}
Don't cache it!
Don’t store a connection in a variable, because another thread might try to use it when it’s already checked back in into the connection pool. See: ActiveRecord::ConnectionAdapters::ConnectionPool
connection = ActiveRecord::Base.connection threads = (1..100).map do Thread.new do begin 10.times do connection.execute("SELECT SLEEP(1)") # WRONG ActiveRecord::Base.connection.execute("SELECT SLEEP(1)") # CORRECT end puts "success" rescue => e puts e.message end end end threads.each(&:join)
reload next time referenced
After calling reset on an association, it will be forced to be reloaded next time it’s referenced. Useful after you manipulate an associated object/collection with SQL, and you want to make sure subsequent uses don’t get the invalid cached version. Better than reload in that it doesn’t actually reload if not needed.
Replacement
Use sanitize or connection.quote instead.
No concurrency
If you want to handle concurrency, this doesn’t work:
a = Article.first b = Article.first a.increment!(:view_count) b.increment!(:view_count) a.reload.view_count # -> 1 b.reload.view_count # -> 1
Instead, use SQL:
def increment_with_sql!(attribute, by = 1) raise ArgumentError("Invalid attribute: #{attribute}") unless attribute_names.include?(attribute.to_s) original_value_sql = "CASE WHEN `#{attribute}` IS NULL THEN 0 ELSE `#{attribute}` END" self.class.update_all("`#{attribute}` = #{original_value_sql} + #{by.to_i}", "id = #{id}") reload end