Howto run a rake task in sandbox mode

If you have a Rails rake task that somehow changes your DB data, but you want to be sure that the DB will be rolled back to its previous state after the rake task has completed, you can simply include this snippet right after your task definition: ActiveRecord::Base.connection.increment_open_transactions ActiveRecord::Base.connection.begin_db_transaction at_exit do ActiveRecord::Base.connection.rollback_db_transaction ActiveRecord::Base.connection.decrement_open_transactions end If you wonder where is this code coming from, it’s directly from the rails console code....

March 10, 2011 · 1 min · metalelf0

Rails 3 scopes with HABTM (has and belongs to many) relations

There are already many posts about this, but maybe this simple example will help you understand this subject even better. # First model: tag.rb # note that pomodori is a custom plural for pomodoro class Tag < ActiveRecord::Base has_and_belongs_to_many :pomodori end # Second model: pomodoro.rb # here is how to define a Rails 3 scope through the join table: class Pomodoro < ActiveRecord::Base has_and_belongs_to_many :tags scope :by_tag, lambda { |tag_text| joins("join pomodori_tags, tags")....

January 28, 2011 · 1 min · metalelf0