...on database statements by default, the following query will run for an entire day: ActiveRecord::Base.connection.execute("SELECT pg_sleep(86400)") The good news is that with statement_timeout for PostgreSQL...

...adapter: postgresql # ... variables: statement_timeout: 10s # or ms, min, etc Test that it works: ActiveRecord::Base.connection.execute("show statement_timeout;").map { |row| row } => [{"statement_timeout"=>"10s"}] begin ActiveRecord::Base.connection.execute("SELECT pg...

api.rubyonrails.org

...you have to explicitly tell rails for each transaction to indeed use proper nesting: ActiveRecord::Base.transaction(joinable: false, requires_new: true) do # inner code end This is a safer default...

...this would do meaningful things and only roll back under certain conditions): class Country < ActiveRecord::Base after_save :do_something def do_something raise ActiveRecord::Rollback end end

...in a money transfer and balances would still be off. Code # app/models/lock.rb class Lock < ActiveRecord::Base def self.acquire(name) already_acquired = definitely_acquired?(name) if already_acquired yield else

before :each do @reader, @writer = IO.pipe end def fork_with_new_connection config = ActiveRecord::Base.remove_connection fork do begin ActiveRecord::Base.establish_connection(config) yield ensure ActiveRecord::Base.remove_connection Process.exit...

api.rubyonrails.org

...This is true, but has some caveats. Example Consider the following models: class Image < ActiveRecord::Base; end class Video < ActiveRecord::Base; end class PageVersion < ActiveRecord::Base belongs_to :primary_medium...

...polymorphic: true # may be Image or Video end class Page < ActiveRecord::Base belongs_to :current_version, class_name: 'PageVersion' end Now, when you load pages and include their current versions...

...below uses embedded models to perform that update: class AddCurrentToVendor < ActiveRecord::Migration class Vendor < ActiveRecord::Base end class Article < ActiveRecord::Base has_many :vendors, :class_name => 'AddCurrentToVendor::Vendor', :order => 'created...

...you have an Invoice with multiple Items. Each Item has a Product: class Invoice < ActiveRecord::Base has_many :items has_many :products, :through => :items end class Item < ActiveRecord::Base

belongs_to :product end class Product < ActiveRecord::Base has_many :items end Further say you have multiple items for the same product and invoice in the items table...

# Given the following models class Image < ActiveRecord::Base has_many :album_images has_many :albums, through: :album_images end class Album < ActiveRecord::Base has_many :album_images

...images, through: :album_images end # Join model class AlbumImage < ActiveRecord::Base belongs_to :album belongs_to :image end Destroying a record in this setup will only remove the record itself...

...you don't have an ActiveRecord class in your scope, you can always use ActiveRecord::Base.transaction do...

By using a transaction we have grouped together the creation of the...

...a single database row, you should always use a transaction. Note that in Rails, ActiveRecord::Base#save automatically opens a transaction. Hence changes you make in callbacks, nested attributes processing...

...lib/ext/active_record/relation.rb class ActiveRecord::Relation def where_array_matches!(array_attribute, expected_values) quoted_column = ActiveRecord::Base.connection.quote_column_name(array_attribute) where!("#{quoted_column} @> array[:expected_values] AND #{quoted_column} <@ array...

...expected_values]", expected_values:) end end # app/models/application_record.rb class ApplicationRecord < ActiveRecord::Base def self.where_array_matches(array_attribute, expected_values) quoted_column = ActiveRecord::Base.connection.quote_column_name(array_attribute) where("#{quoted_column...

...this script with e.g. `rails runner lib/scripts/benchmark.rb` require 'open3' # For debugging # Rails.logger = Logger.new(STDOUT) # ActiveRecord::Base.logger = Logger.new(STDOUT) ITERATIONS = 100 PERCENTILE = 0.95 def system!(*) stdout_str, error_str, status = Open3.capture3...

...time = Benchmark.measure { eval(benchmark) }.real measurements[benchmark] << real_time puts [real_time.round(3), benchmark].inspect ActiveRecord::Base.connection.clear_query_cache ActiveRecord::Base.connection_pool.release_connection system!('sudo service postgresql stop') system!('sync') system!("sudo...

makandra dev
impactahead.com

...app.response.status app.response.parsed_body Using helpers helper.some_helper_method Examining the database schema List tables: ActiveRecord::Base.connection.tables List columns: ActiveRecord::Base.connection.columns($table_name...

makandra dev
github.com

...not always faster, but in this case, it is: class FatModelsController def index result = ActiveRecord::Base.connection.execute(Arel.sql(<<-SQL)) SELECT jsonb_agg( jsonb_build_object('name', indexed_attribute_1) ) AS aggregated...

first.aggregated_names end def self.refresh if pick(:last_refreshed_at) < FatModel.maximum(:updated_at) ActiveRecord::Base.connection.execute("REFRESH MATERIALIZED VIEW fat_models_materialized_json") end end end class FatModelsController

...name of the model that connects to the second database. For example: class MigrationRecord < ActiveRecord::Base self.abstract_class = true connects_to database: { writing: :my_app_migration, reading: :my_app_migration...

...in your database.yml, Rails needs to decide which one to pick. Any instance of ActiveRecord::Base will connect to the primary database by default - unless you told it to use...

...for the item's unit price. Now we implement our Item model: class Item < ActiveRecord::Base validates_numericality_of :unit_price, :quantity def total (unit_price * quantity).round(2)

...are listed as net prices, we implement our Invoice model like this: class Invoice < ActiveRecord::Base VAT_RATE = BigDecimal('0.19') has_many :items def totals totals = {} totals[:net] = items.sum(&:total...

...enum attribute interface By default Rails is mapping enum attributes to integers: class Conversation < ActiveRecord::Base enum :status, [ :active, :archived ] end class CreateConversations < ActiveRecord::Migration[7.1] def change create_table...

...still possible to map the enum attribute to an enumerated database type: class Conversation < ActiveRecord::Base enum :status, active: 'active', archived: 'archived' end class CreateConversations < ActiveRecord::Migration[7.1]

...add_index :users, [:last_name, :created_at] 3. Test the index in your database ActiveRecord::Base.connection.execute('SET enable_seqscan = OFF') # Try to force index only scan even seq scan is...

explain = "EXPLAIN ANALYSE #{query}" ActiveRecord::Base.connection.execute(explain).each {|result| puts result} # => {"QUERY PLAN"=>"Index Scan using index_users_on_last_name_and_created_at on users (cost...

...of the same association. Example with a has_many / belongs_to association: class Forum < ActiveRecord::Base has_many :posts, inverse_of: :forum end class Post < ActiveRecord::Base belongs_to :forum...

makandra dev

before :each do @reader, @writer = IO.pipe end def fork_with_new_connection config = ActiveRecord::Base.remove_connection fork do begin ActiveRecord::Base.establish_connection(config) yield ensure ActiveRecord::Base.remove_connection Process.exit...

end ActiveRecord::Base.establish_connection(config) end it 'should synchronize processes on the same lock' do (1..20).each do |i| fork_with_new_connection do @reader.close ActiveRecord::Base.connection.reconnect! Lock.acquire...

...this is to change an association inside a form model, like this: class Credential < ActiveRecord::Base end class User < ActiveRecord::Base has_many :credentials end class SignUpCredential < ActiveType::Record[Credential...

...relevant methods, it is suggested to subtract generic methods like this: User.methods - Object.methods User.methods - ActiveRecord::Base.methods @user.methods - Object.instance_methods @user.methods - ActiveRecord::Base.instance_methods

...objects will not be validated when this object is saved. Setup # post.rb class Post < ActiveRecord::Base has_one :attachment end # attachment.rb class Attachment < ActiveRecord::Base belongs_to :post validates :title...

...you use PostgreSQL, read this instead.) Say you have a user model class User < ActiveRecord::Base validates_uniqueness_of :name end with a unique index in the database.

...due to duplicate index key. You can change Rails' behaviour, by saying class User < ActiveRecord::Base validates_uniqueness_of :name, case_sensitive: false end When you get an ActiveRecord::RecordNotUnique...

makandra dev

...may lead to some trouble. Let's exemplify that using this example: class Project < ActiveRecord::Base has_one :note end class Note < ActiveRecord::Base belongs_to :project end

...as the associated object is not present when creating a new Project. class Note < ActiveRecord::Base validates_presence_of :description, :if => Proc.new { |note| note.project.description.present? } ... This does not work when creating...

...look good, it will actually cause all kinds of trouble: def with_other_database ActiveRecord::Base.establish_connection(slave_settings) yield ensure ActiveRecord::Base.establish_connection(master_settings) end Putting aside that...

...require to abort the transaction). A better approach As a general rule, never use ActiveRecord::Base.establish_connection and also don't use establish_connection on your other ActiveRecord classes. Instead...