# ActiveRecord

Published articles for ActiveRecord.

This is one page of public article previews, not the complete archive. Follow Next page to continue. Summaries are not the original full articles.

## Testing Readonly Models

DevFeed: [Testing Readonly Models](<https://devfeed.tech/articles/testing-readonly-models-20120.md>)

Original publisher: [Read original article](<https://hashrocket.com/blog/posts/testing-readonly-models>)

Author: Tony Yunker

Published: 2026-03-17T13:00:00Z

Content type: tutorial

Language: en

Sources: [Hashrocket](<https://devfeed.tech/sources/hashrocket.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Testing](<https://devfeed.tech/topics/testing.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Databases](<https://devfeed.tech/topics/databases.md>), [Code](<https://devfeed.tech/topics/code.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [code](<https://devfeed.tech/tags/code.md>), [database](<https://devfeed.tech/tags/database.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [ruby-on-rails](<https://devfeed.tech/tags/ruby-on-rails.md>), [testing](<https://devfeed.tech/tags/testing.md>)

### AI overview

A Rails tutorial explains how to test readonly models that normally reject database writes. It proposes a narrowly scoped test-only override that temporarily permits persistence during setup and restores readonly behavior before the test runs.

### Source excerpt

I was working with a readonly model in Rails the other day and ran into an issue whilst testing it. Here's what I ran into and the solution I came up with. Readonly models are a great way to signal that, well, you should only ever read them, not write them. Maybe you have some external system that connects to the database for writes, or maybe your Rails app connects to some data warehouse for some queries or reports. It's can be useful to have a safeguard to prevent accidental errant writes. It's actually really simple to make a model readonly, you just need to override the readonly? method: class ReadOnlyPost < ApplicationRecord def readonly? = true end Now any attempt to create/save/update/delete a ReadOnlyPost will raise a friendly ActiveRecord::ReadOnlyRecord exception. The Problem You might be able to see where this is going. For any tests that can avoid saving this readonly model to the database, (i.e. using ReadOnlyPost.new or FactoryBot.build), then we're all good. But often tests need to persist some records to the test database. And if I try to create a ReadOnlyPost, I'm going to have a bad time. RSpec.describe ReadOnlyPost, type: :model do let(:post) { ReadOnlyPost.create(title: "Title", body: "body") } it "can create a post" do expect(post).to be_a(ReadOnlyPost) end end % bundle exec rspec F Failures: 1) ReadOnlyPost can create a post Failure/Error: let(:post) { ReadOnlyPost.create(title: "Title", body: "body") } ActiveRecord::ReadOnlyRecord: ReadOnlyPost is marked as readonly # ./spec/models/read_only_post_spec.rb:4:in `block (2 levels) in <top (required)>' # ./spec/models/read_only_post_spec.rb:7:in `block (2 levels) in <top (required)>' This makes sense, the readonly property of the model doesn't go away in test - creating a record is creating a record is writing to the database, so it will fail. The Solution What we want to do is override this constraint to temporarily allow us to persist data. Ideally, we do this very narrowly to not impact the syst

## Speed Up Your Rails App by Squashing N+1 Queries

DevFeed: [Speed Up Your Rails App by Squashing N+1 Queries](<https://devfeed.tech/articles/speed-up-your-rails-app-by-squashing-n-1-queries-20119.md>)

Original publisher: [Read original article](<https://hashrocket.com/blog/posts/speed-up-your-rails-app-by-squashing-n-1-queries>)

Author: Tony Yunker

Published: 2025-11-20T14:00:00Z

Content type: tutorial

Language: en

Sources: [Hashrocket](<https://devfeed.tech/sources/hashrocket.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Databases](<https://devfeed.tech/topics/databases.md>), [Code](<https://devfeed.tech/topics/code.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [code](<https://devfeed.tech/tags/code.md>), [database](<https://devfeed.tech/tags/database.md>), [performance](<https://devfeed.tech/tags/performance.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby-on-rails](<https://devfeed.tech/tags/ruby-on-rails.md>)

### AI overview

This tutorial explains how N+1 queries arise in Rails applications when associated ActiveRecord records are accessed during iteration. It uses nested authors, posts, and tags as a case study, showing how eager loading can reduce a workload from 1,101 database queries to 3.

### Source excerpt

N+1 queries are one of the most common performance killers in Rails apps, but also one of the easiest to fix. In this post, we'll see how a single line of code can reduce 1,101 database queries down to 3. N+1s occur in rails when you have associated ActiveRecord models, and iterate over one model while accessing fields on the associated records. This might be easier to explain with an example. Let's say you have the following ActiveRecord models: class Author < ApplicationRecord has_many :posts end class Post < ApplicationRecord belongs_to :author has_many :tags end class Tag < ApplicationRecord belongs_to :post end An author has many posts, and each post can have many tags. If we want to list each author and their blog posts like below, then we'll make 1 query to the database for the authors, and then another query for each author's blog posts. For N authors, that's 1 + N queries to the database. Author.take(3).each do |author| puts author.name author.posts.each do |post| puts post.title end end We can see all the queries in the logs - 1 query for authors, then 3 queries for each author's blog posts: Author Load (31.4ms) SELECT "authors".* FROM "authors" Post Load (2.4ms) SELECT "posts".* FROM "posts" WHERE "posts"."author_id" = 163 Post Load (0.4ms) SELECT "posts".* FROM "posts" WHERE "posts"."author_id" = 164 Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."author_id" = 165 In small doses this isn't a big deal - these are small, quick queries. However, as soon as the data gets larger, the queries more complex, or the cardinality of these queries grow, then things can really slow down. Let's look at a case study, where we start with an unoptimized query with 2 layers of N+1s, and see how much faster we can make it. Case 1 - The Unoptimized Query Let's take the example above, and add another layer to it. On our authors index page, we want to list each author, then each of their blog posts, including their associated tags. With a totally unoptimized qu

## Turso Adds Ruby on Rails Support

DevFeed: [Turso Adds Ruby on Rails Support](<https://devfeed.tech/articles/turso-adds-ruby-on-rails-support-6057.md>)

Original publisher: [Read original article](<https://turso.tech/blog/turso-adds-ruby-on-rails-support>)

Author: Levy Albuquerque

Published: 2024-12-18T00:00:00Z

Content type: article

Language: en

Sources: [Turso Blog](<https://devfeed.tech/sources/turso-blog.md>)

Topics: [Turso](<https://devfeed.tech/topics/turso.md>), [Rails](<https://devfeed.tech/topics/rails.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Embedded Replicas](<https://devfeed.tech/topics/embedded-replicas.md>), [CRUD](<https://devfeed.tech/topics/crud.md>), [migration](<https://devfeed.tech/topics/migration.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [embedded-replicas](<https://devfeed.tech/tags/embedded-replicas.md>), [latency](<https://devfeed.tech/tags/latency.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [ruby-on-rails](<https://devfeed.tech/tags/ruby-on-rails.md>), [sql](<https://devfeed.tech/tags/sql.md>), [testing](<https://devfeed.tech/tags/testing.md>), [turso](<https://devfeed.tech/tags/turso.md>)

### AI overview

Turso announces a technical-preview Ruby gem for ActiveRecord with Rails support. The article explains how to configure Turso in Rails, use embedded replicas to work offline and reduce network latency, run migrations, and perform CRUD operations. It also demonstrates usage with standalone Ruby applications and Sinatra.

### Source excerpt

Today we are excited to announce the first technical preview of the Rubygem for ActiveRecord that supports Rails.

## Rails Tip : When You Are Testing Model Files without a Database Table Delete Fixtures File

DevFeed: [Rails Tip : When You Are Testing Model Files without a Database Table Delete Fixtures File](<https://devfeed.tech/articles/rails-tip-when-you-are-testing-model-files-without-a-database-table-delete-fixtures-file-28291.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2022/07/20/rails-tip-when-you-are-testing-model-files-without-a-database-table-delete-fixtures-file.html>)

Author: Fuzzygroup

Published: 2022-07-20T14:02:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Testing](<https://devfeed.tech/topics/testing.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [factorybot](<https://devfeed.tech/tags/factorybot.md>), [flow-analytics](<https://devfeed.tech/tags/flow-analytics.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [software-testing](<https://devfeed.tech/tags/software-testing.md>), [testing](<https://devfeed.tech/tags/testing.md>)

### AI overview

A Rails testing tip explaining that model tests without a backing database table can fail when Rails tries to load an unintended fixture file. Deleting the fixture file prevents the test runner from querying the missing table; the article also notes that FactoryBot suppresses fixture creation.

### Source excerpt

I generate a lot of models without ActiveRecord backing. The reason for this is I try and follow a fairly functional style of Ruby coding where I use class methods. The reason I use models for this: I don't know what to call them other than a model The models directly is auto loaded so I can refresh it with reload! in Rails console My normal process for this: rails g foo Delete the migration Delete the "< ..." at the top i.e. the inherits from ActiveRecord stff; exact syntax varies from Rails version to Rails version Today I hit this error when running a test and it puzzled me: Error: VolumeCommonTest#test_it_should_have_the_right_values_for_cubic_feet_of_water: ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "volume_commons" does not exist LINE 9: WHERE a.attrelid = '"volume_commons"'::regclass This actually took me a bit to figure out. Here's the tldr: It was coming from bin/rails test test/models/volume_common.rb It was the result of the test runner trying to load the fixture file. The reason this was surprising was that I normally customize each Rails project with ThoughtBot's FactoryBot gem and this time I forgot. FactoryBot suppresses fixture file creation but since I screwed up, it was there and tried to get loaded into a missing table. And, yes, the error is mine since I didn't read it well but at times like these I wish for a gem called abusive_error messages which sees "PG::UndefinedTable" and shouts out something like: Yo! Hoser! Where be da database table ? Ah if there were only infinite time to craft the software tools we really want ...

## Fixing FactoryBot Validation Name Has Already Been Taken Controller Test or Spec Errors

DevFeed: [Fixing FactoryBot Validation Name Has Already Been Taken Controller Test or Spec Errors](<https://devfeed.tech/articles/fixing-factorybot-validation-name-has-already-been-taken-controller-test-or-spec-errors-28117.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/2022/06/10/fixing-factorybot-validation-name-has-already-been-taken-controller-test-or-spec-errors.html>)

Author: Fuzzygroup

Published: 2022-06-10T12:41:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Testing](<https://devfeed.tech/topics/testing.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Development](<https://devfeed.tech/topics/development.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [bug](<https://devfeed.tech/tags/bug.md>), [controllers](<https://devfeed.tech/tags/controllers.md>), [development](<https://devfeed.tech/tags/development.md>), [factorybot](<https://devfeed.tech/tags/factorybot.md>), [rails](<https://devfeed.tech/tags/rails.md>), [testing](<https://devfeed.tech/tags/testing.md>), [tests](<https://devfeed.tech/tags/tests.md>)

### AI overview

This troubleshooting article examines recurring ActiveRecord "Name has already been taken" failures in FactoryBot-backed Rails controller tests. It describes investigating associations, test data, database cleaning, and model accessors while tracing the source of the validation behavior.

### Source excerpt

So, last night, whilst pulling vampire hours on writing tests - always, always, always a bad idea - I encountered multiple variants on this bug: ❯ bundle exec rails test test/controllers/links_controller_test.rb:44 Running 7 tests in a single process (parallelization threshold is 50) Run options: --seed 21798 # Running: E Error: LinksControllerTest#test_should_get_edit: ActiveRecord::RecordInvalid: Validation failed: Name has already been taken test/controllers/links_controller_test.rb:47:in `block in <class:LinksControllerTest>' This was particularly vexing because while the object in question did have a name attribute, it did not have name validations: ######################################################################### # # validations # ######################################################################### validates_presence_of :project_id validates_presence_of :team_id validates_presence_of :account_id validates_presence_of :link_type_id There are a number of people on the internet that have this issue including this stack overflow post. What I noticed as I researched this is that I only saw it in controller tests. Also my model tests continued to function correctly without any validation issues. I had initially discovered this while working on my RodAuth testing deep dive and back burnered it until I got past that particularly nasty kettle of fix. I was working with two objects, link and project and project only through an association. So my Factory for link looked like this: FactoryBot.define do factory :link do url { "https://www.example.com/?time=#{Time.now.to_i}" } name { "Cartazzi App on development #{Time.now.to_i}" } active { true } association :account association :team association :project association :link_type end end You will notice the insane use of Time.now.to_i to try and generate more distinct data. This was an attempt to see if maybe some kind of hidden validation was present (it is ruby and everything is dynamic; who knows where a monk

## Why You Should Avoid Models in Rails Migrations

DevFeed: [Why You Should Avoid Models in Rails Migrations](<https://devfeed.tech/articles/why-you-should-avoid-models-in-rails-migrations-21078.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2021/04/10/avoid-models-in-migrations/>)

Published: 2021-04-10T12:00:00Z

Content type: article

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [migration](<https://devfeed.tech/topics/migration.md>), [Code](<https://devfeed.tech/topics/code.md>), [Databases](<https://devfeed.tech/topics/databases.md>), [App](<https://devfeed.tech/topics/app.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [code](<https://devfeed.tech/tags/code.md>), [database](<https://devfeed.tech/tags/database.md>), [migration](<https://devfeed.tech/tags/migration.md>), [rails](<https://devfeed.tech/tags/rails.md>), [us](<https://devfeed.tech/tags/us.md>)

### AI overview

This article explains why Rails migrations should avoid relying on application models. A model rename can cause an older migration that calls the model to fail when another developer runs it later. It recommends using SQL through the base database connection or defining a temporary model inside the migration so migrations depend on stable database structure rather than changing application code.

### Source excerpt

Humble Beginnings A simple Rails application exists with two models, Books and Authors. class Book < ApplicationRecord belongs_to :author end class Author < ApplicationRecord has_many :books end After some domestic success, this simple Rails app goes international. A new column is required on the books table: country to denote which country published the Book. A Reasonable Migration To preserve data integrity, the country column should not allow null since null isn't a country. Existing books also need to have a country set. This is all accomplished within a single migration in 3 steps: Add a column Update column for existing books with a reasonable value Add a constraint that the column can not be null class AddCountryToBooks < ActiveRecord::Migration[6.1] def up add_column :books, :country, :string, length: 2 Book.update_all(country: 'US') change_column_null :books, :country, false end def down remove_column :books, :country end end This migration does the job but has hidden implications. A developer working in isolation may never run into the trap lurking in this code, but a team could. Working with Others Two developers work on this application, divvying up the wild world of books and authors but maintaining healthy work life balances. One developer goes on vacation and has a surprise waiting for them when they return. Developer 1 👩💻 Developer 2 👨💻 Day 1 Write Code Write Code Day 2 😎 Time Off 🏗 Create Migration Day 3 😎 Time Off 📛 Rename Class Day 4 😎 Time Off Write Code Day 5 Run Migrations -> 🔥 Error Write Code While Developer 1 was away, the Developer 2 was busy. They wrote the above migration, updated existing data and then a new feature request was completed: A model rename. Developer 1 returns, updates their local environment, and runs rake db:migrate: == 20210407191819 AddCountryToBooks: migrating =================== -- add_column(:books, :country, :string, {:length=>2}) -> 0.0015s rake aborted! StandardError: An error has occurred, this and all la

## Restart ID sequences in Postgres on Truncation

DevFeed: [Restart ID sequences in Postgres on Truncation](<https://devfeed.tech/articles/restart-id-sequences-in-postgres-on-truncation-28329.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/sql/2020/03/13/restart-id-sequences-in-postgres-on-truncation.html>)

Author: Fuzzygroup

Published: 2020-03-13T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Database](<https://devfeed.tech/topics/database.md>), [Rails](<https://devfeed.tech/topics/rails.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [csv](<https://devfeed.tech/tags/csv.md>), [debugging](<https://devfeed.tech/tags/debugging.md>), [id](<https://devfeed.tech/tags/id.md>), [identifier](<https://devfeed.tech/tags/identifier.md>), [postgres](<https://devfeed.tech/tags/postgres.md>), [rails](<https://devfeed.tech/tags/rails.md>), [sequences](<https://devfeed.tech/tags/sequences.md>), [sql](<https://devfeed.tech/tags/sql.md>)

### AI overview

A tutorial on resetting PostgreSQL ID sequences when truncating tables, including a Rails implementation using ActiveRecord. Resetting sequences keeps identifiers consistent when rebuilding data from the same CSV files in development and production.

### Source excerpt

Note: This is from a real world thing that I'm about to release. Like a lot of database apps in the world, mine generally tend to use auto incrementing ids for object identifiers. An object identifier is a value in a system which uniquely identifies something. Let's say you have a url like this: http://localhost:3169/locations?country_id=91 What that is saying, under the hood, is "Get the data from the locations store and give me the object with id value 91". The thing that I'm currently building is populated with a bunch of data which is coming from CSV files that I'm loading from the Internet and I need to wipe the data in the system every time it rebuilds. Now when I say location store, I mean, in this case, a locations table in a Postgres database. When you wipe the contents of a table in Postgres you end up with the next object in the table getting the last ID value plus 1. The secret is to add this snippet to your truncation routine: RESTART IDENTITY or in full: TRUNCATE states RESTART IDENTITY And in Rails I have this implemented on all my core classes as: def self.truncate ActiveRecord::Base.connection.execute("TRUNCATE states RESTART IDENTITY") end Since this is a def self., think of it as a C style static thing. By defining it this way, I can simply call it as State.truncate to eliminate all data in my states store (ok its is a table but it could be more complex) and restart my ID sequences. And in cases it wasn't clear exactly why you want this, since I'm processing the same data files in Production as in Development, my bookmarks become consistent allowing easier debugging.

## Ruby Testing Technique - The Power and Stupidity of def foo

DevFeed: [Ruby Testing Technique - The Power and Stupidity of def foo](<https://devfeed.tech/articles/ruby-testing-technique-the-power-and-stupidity-of-def-foo-28300.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rspec/2020/01/03/ruby-testing-technique-the-power-and-stupidity-of-def-foo.html>)

Author: Fuzzygroup

Published: 2020-01-03T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Testing](<https://devfeed.tech/topics/testing.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Software Engineering](<https://devfeed.tech/topics/software-engineering.md>), [Rails](<https://devfeed.tech/topics/rails.md>), [Database](<https://devfeed.tech/topics/database.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [database](<https://devfeed.tech/tags/database.md>), [factorybot](<https://devfeed.tech/tags/factorybot.md>), [rails](<https://devfeed.tech/tags/rails.md>), [rspec](<https://devfeed.tech/tags/rspec.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [testing](<https://devfeed.tech/tags/testing.md>), [validation](<https://devfeed.tech/tags/validation.md>)

### AI overview

A Ruby testing troubleshooting article describes debugging a failing FactoryBot factory for an Objective record in a Rails side project. The supplied excerpt identifies validation errors involving missing User and Organization associations and begins a technique of adding class and instance methods named foo to investigate the problem, but it ends before documenting the complete resolution.

### Source excerpt

I had an abysmal day yesterday coding on my side project. Ok - coding on one of my side projects. I had one of those days where you try to do something simple and NOTHING, NOT ONE DAMN THING, WORKS. Note: Every software engineer knows this type of day. They aren't days that you talk about with anyone in your life because you spend hours failing at something that you know is so damn simple that, if you can't make it work, you should honestly give up software engineering and go cut grass for a living. I refer to these days, when I have them, as spirit crushers / brain emasculators. And when they occur, I find that a nap (or a snickers bar) is the best medicine. All I was trying to do was make a simple factory work. For those who aren't deeply immersed in the world of software testing in ruby, a factory is a software method which creates a sample object that represents the actual object so it can be tested. Factories are used in place of actual objects, generally, because they run faster. Here was the definition of the factory: FactoryBot.define do factory :objective do name {Faker::Name.first_name} user organization objective_type okr_team quarter end end All this means is: Create an object named objective Give it a name attribute that is pulled from a library called Faker using the first_name method Give it a relationship back to the user object Give it a relationship back to the organization object Give it a relationship back to the objective_type object Give it a relationship back to the okr_team object Give it a relationship back to the quarter object Although this might seem complex, it is actually drop dead simple and something that I've probably done hundreds if not thousands of times. And yet, yesterday, all I could get was some variant on this censored backtrace: ActiveRecord::RecordInvalid: Validation failed: Organization must exist, User can't be blank, Organization can't be blank # /Users/sjohnson/.rvm/gems/ruby-2.6.5/gems/fabrication-2.21.0/lib/fabricatio

## How Do You Know What ActiveRecord Table Has a user\_id Attribute?

DevFeed: [How Do You Know What ActiveRecord Table Has a user\_id Attribute?](<https://devfeed.tech/articles/how-do-you-know-what-activerecord-table-has-a-user-id-attribute-28248.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2019/12/28/how-do-you-know-what-activerecord-table-has-a-user-id-attribute.html>)

Author: Fuzzygroup

Published: 2019-12-28T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Development](<https://devfeed.tech/topics/development.md>), [data-modeling](<https://devfeed.tech/topics/data-modeling.md>), [business logic](<https://devfeed.tech/topics/business-logic.md>)

Tags: [active-record](<https://devfeed.tech/tags/active-record.md>), [activerecord](<https://devfeed.tech/tags/activerecord.md>), [business-logic](<https://devfeed.tech/tags/business-logic.md>), [class](<https://devfeed.tech/tags/class.md>), [classes](<https://devfeed.tech/tags/classes.md>), [console](<https://devfeed.tech/tags/console.md>), [development](<https://devfeed.tech/tags/development.md>), [id](<https://devfeed.tech/tags/id.md>), [jumpstart](<https://devfeed.tech/tags/jumpstart.md>), [metaprogramming](<https://devfeed.tech/tags/metaprogramming.md>), [migration](<https://devfeed.tech/tags/migration.md>), [migrations](<https://devfeed.tech/tags/migrations.md>), [rails](<https://devfeed.tech/tags/rails.md>), [relationships](<https://devfeed.tech/tags/relationships.md>), [schema](<https://devfeed.tech/tags/schema.md>), [table](<https://devfeed.tech/tags/table.md>)

### AI overview

This article explains how to identify application classes whose ActiveRecord-backed tables have a user_id attribute. It introduces a DataObject class with a .has_user_id method that can be run in the console, helping the author add belongs_to user relationships without repeatedly checking the schema.

### Source excerpt

Even though I'm a firm, firm believer in agile, I've recently been experimenting with a throwback to waterfall style development and it very quickly left me with a fully featured data structure of tables and relationships modeled as example data. What I did is very rapidly write a series of migrations and then populate them to represent a sample "installation". My goal with this approach was to play to my strengths - data modeling - and avoid getting tied down in user interface stuff (my weakness). This was a very, very interesting approach and what I found was that I got much further along the lines of the "guts" of an application simply because I never got discouraged by: Oh Shite - I know this should look good but I'm too much of a hoser to make it look good; I guess I'll put it aside and go watch TV The downside to this is that I never bothered setting up the normal associations that you do when you write a migration; I simply thought about this application in terms of the example data: the users who would be using the system the data objects that they would create how the data objects would interact with each other One of the things that I noticed when I started filling in the basics like "belongs_to :user" was that I kept constantly jumping between the class I was working on and the schema file. Finally it hit me - what I needed was a method that I could execute in the console that would tell me what classes had a user_id attribute. And so I wrote a class called DataObject (for an ActiveRecord class which stores data) and a method .has_user_id. What I was looking for was output that looked like this: > DataObject.has_user_id Initiative Yes - has a user_id field KeyResultOwner Yes - has a user_id field KeyResult Yes - has a user_id field ObjectiveOwner Yes - has a user_id field ObjectiveType Objective Yes - has a user_id field OkrTeamMember Yes - has a user_id field OkrTeam Yes - has a user_id field OrganizationGroup Organization Quarter ResponsibilityRole Stat

## Adding an Includes Clause to ActiveRecord and Watching the Joy Flow

DevFeed: [Adding an Includes Clause to ActiveRecord and Watching the Joy Flow](<https://devfeed.tech/articles/adding-an-includes-clause-to-activerecord-and-watching-the-joy-flow-28245.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2019/11/18/adding-an-includes-clause-to-activerecord-and-watching-the-joy-flow.html>)

Author: Fuzzygroup

Published: 2019-11-18T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [SQL](<https://devfeed.tech/topics/sql.md>), [bug](<https://devfeed.tech/topics/bug.md>), [Databases](<https://devfeed.tech/topics/databases.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [bug](<https://devfeed.tech/tags/bug.md>), [performance](<https://devfeed.tech/tags/performance.md>), [rails](<https://devfeed.tech/tags/rails.md>), [sql](<https://devfeed.tech/tags/sql.md>)

### AI overview

This article explains how repeated ActiveRecord queries created an N+1 query problem and shows that adding .includes(:metric_type) to the query fixes the issue by loading the associated metric types together.

### Source excerpt

I've written in the past about watching your SQL queries stream by in the Rails console and how seeing, well, stupidity / things that look wrong can help guide you to things you need to find. Here's an example I witnessed recently: habit = Habit.find(2) habit.total_this_month Metric Load (2.5ms) SELECT metrics.date_created_at, metrics.int_val, metrics.float_val, metrics.metric_type_id FROM metrics WHERE metrics.habit_id = 2 AND (date_created_at >= '2019-11-01') AND (date_created_at <= '2019-11-30') MetricType Load (3.3ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (38.1ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (17.0ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (40.3ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (2.7ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (1.3ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (3.2ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (5.2ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (252.9ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (11.2ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (7.4ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 MetricType Load (1.6ms) SELECT metric_types.* FROM metric_types WHERE metric_types.id = 1 LIMIT 1 According to the bug tracker where I logged, this it was logged 5 days ago (so on November 12). And if you could the number of metric_type queries above, the total is 12. This is date ordered stuff so it is pretty obvious that what's happening is that metric_type query is getting executed once per day. Here's the

## Implementing Safe ActiveRecord Like Queries for Rails

DevFeed: [Implementing Safe ActiveRecord Like Queries for Rails](<https://devfeed.tech/articles/implementing-safe-activerecord-like-queries-for-rails-28243.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2019/11/11/implementing-safe-activerecord-like-queries.html>)

Author: Fuzzygroup

Published: 2019-11-11T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [SQL](<https://devfeed.tech/topics/sql.md>), [Databases](<https://devfeed.tech/topics/databases.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [database](<https://devfeed.tech/tags/database.md>), [limit](<https://devfeed.tech/tags/limit.md>), [parameter](<https://devfeed.tech/tags/parameter.md>), [rails](<https://devfeed.tech/tags/rails.md>), [sql](<https://devfeed.tech/tags/sql.md>), [table](<https://devfeed.tech/tags/table.md>)

### AI overview

A Rails tutorial explains how to build safer ActiveRecord LIKE queries using Arel table fields and parameterized query construction. It demonstrates searching a Metric model's note field with filtering, ordering, limits, and pagination.

### Source excerpt

In any SQL based database, a like query is generally an SQL injection attack waiting to happen because the underlying sql statement looks like this: SELECT id FROM posts WHERE name LIKE '%foo%' Note: A 30 year old thank you goes out to InfoWorld and Joe Celko who beat into his reader's brains the concept of capitalizing SQL statements for better legibility. Thank you Joe. A seemingly solid StackOverflow post gives this recommendation: title = Model.arel_table[:title] Model.where(title.matches("%#{query}%")) Please note that Model needs to be replaced with the name of your table. Let's say that our table was named Metric and we have a normal simple_form object for Metric coming into our Rails app with a parameter named q and we have a real world Rails app with a limit clause and pagination. Here's how this would look: @q = params[:metric][:q] note = Metric.arel_table[:note] @metrics = current_user.metrics.where(note.matches("%#{@q}%")).order("date_created_at desc").limit(@limit).page(params[:page]) So: @q represents the incoming query note represents the field in our Metrics table that we want to search agains @metrics is the collection of data returned by the search and the where clause is "note.matches("%#{@q}%")" to find any instances of the term @q within the note field

## Stupid Simple ActiveRecord Optimizations or Why Rails Console is Essential for Development

DevFeed: [Stupid Simple ActiveRecord Optimizations or Why Rails Console is Essential for Development](<https://devfeed.tech/articles/stupid-simple-activerecord-optimizations-or-why-rails-console-is-essential-for-development-28241.md>)

Original publisher: [Read original article](<http://fuzzyblog.io/blog/rails/2019/11/05/stupid-simple-activerecord-optimizations-or-why-rails-console-is-essential-for-development.html>)

Author: Fuzzygroup

Published: 2019-11-05T00:00:00Z

Content type: tutorial

Language: en

Sources: [Scott Johnson](<https://devfeed.tech/sources/scott-johnson.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Optimization](<https://devfeed.tech/topics/optimization.md>), [Development](<https://devfeed.tech/topics/development.md>), [Database](<https://devfeed.tech/topics/database.md>), [Code](<https://devfeed.tech/topics/code.md>)

Tags: [active-record](<https://devfeed.tech/tags/active-record.md>), [activerecord](<https://devfeed.tech/tags/activerecord.md>), [code](<https://devfeed.tech/tags/code.md>), [console](<https://devfeed.tech/tags/console.md>), [database](<https://devfeed.tech/tags/database.md>), [development](<https://devfeed.tech/tags/development.md>), [optimization](<https://devfeed.tech/tags/optimization.md>), [rails](<https://devfeed.tech/tags/rails.md>)

### AI overview

The article explains how Rails console can reveal repeated database queries caused by repeated ActiveRecord association access. It demonstrates rewriting a method to store the associated goal in a local variable, reducing repeated reads and potentially improving both production and development performance without relying on server-side caching.

### Source excerpt

Ever since 2008 when my pairing partner at the time, Jared, pushed me to basically live in the Rails console, I've been heavily, heavily dependent on the console as an essential developer tool. I just watched something that pointed out to me just why it is so damn important. Here's what I observed: 2.6.3 :057 > m.change_pct_today_over_goal? Goal Load (65.2ms) SELECT `goals`.* FROM `goals` WHERE `goals`.`habit_id` = 39 ORDER BY `goals`.`id` ASC LIMIT 1 Habit Load (0.4ms) SELECT `habits`.* FROM `habits` WHERE `habits`.`id` = 39 LIMIT 1 Goal Load (0.5ms) SELECT `goals`.* FROM `goals` WHERE `goals`.`habit_id` = 39 ORDER BY `goals`.`id` ASC LIMIT 1 Goal Load (30.2ms) SELECT `goals`.* FROM `goals` WHERE `goals`.`habit_id` = 39 ORDER BY `goals`.`id` ASC LIMIT 1 true I simply can't think that the fact that we're loading the goal from the database 3 times is an optimal use of computing resources. So I dug into the code and here's what I saw: # original def change_pct_today_over_goal? return false if self.goal.nil? return false if self.habit.goal.amount.nil? goal_amount = self.goal.amount.to_f actual_amount = self.amount amount_over_goal = actual_amount - goal_amount return false if amount_over_goal < 0 return false if amount_over_goal == 0 return true if (amount_over_goal / goal_amount).to_f * 100 >= 25.0 return false end The first 3 lines in the method above walk database associations back to the goal. The simple optimization is to store the goal in a local variable so it is only read once: # rewritten def change_pct_today_over_goal? goal = self.goal return false if goal.nil? return false if goal.amount.nil? goal_amount = goal.amount.to_f actual_amount = self.amount amount_over_goal = actual_amount - goal_amount return false if amount_over_goal < 0 return false if amount_over_goal == 0 return true if (amount_over_goal / goal_amount).to_f * 100 >= 25.0 return false end Now it is possible that with the right caching strategy server side, this change wouldn't be necessary but

## Hooking in a Stats module in Rails Active Record

DevFeed: [Hooking in a Stats module in Rails Active Record](<https://devfeed.tech/articles/hooking-in-a-stats-module-in-rails-active-record-39610.md>)

Original publisher: [Read original article](<https://www.gauravsarma.com/posts/2019-06-09_Hooking-in-a-Stats-module-in-Rails-Active-Record-942c4fdbc0a9>)

Published: 2019-06-09T00:00:00Z

Content type: tutorial

Language: en

Sources: [Gaurav Sarma's Blog](<https://devfeed.tech/sources/gaurav-sarma-s-blog.md>)

Topics: [Ruby on Rails](<https://devfeed.tech/topics/ruby-on-rails.md>), [Object-relational mapping](<https://devfeed.tech/topics/orm.md>), [Programming](<https://devfeed.tech/topics/programming.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [crud](<https://devfeed.tech/tags/crud.md>), [orm](<https://devfeed.tech/tags/orm.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>)

### AI overview

This tutorial explains how to integrate a separate statistics module into Rails Active Record by overriding model CRUD methods and tracking operation counts. It also describes why this approach does not fully handle chained ActiveRecord::Relation queries.

### Source excerpt

Most full-fledged web frameworks come with ORMs built in. ORMs or Object Relational Mappings help to map the programming language data structures to actual data stores without having to worry about the underlying data source...

## An analysis of memory bloat in Active Record 5.2

DevFeed: [An analysis of memory bloat in Active Record 5.2](<https://devfeed.tech/articles/an-analysis-of-memory-bloat-in-active-record-5-2-41347.md>)

Original publisher: [Read original article](<https://samsaffron.com/archive/2018/06/01/an-analysis-of-memory-bloat-in-active-record-5-2>)

Author: Sam Saffron

Published: 2018-06-01T07:07:15Z

Content type: article

Language: en

Sources: [Sam Saffron](<https://devfeed.tech/sources/sam-saffron.md>)

Topics: [Ruby](<https://devfeed.tech/topics/ruby.md>), [Rails](<https://devfeed.tech/topics/rails.md>), [Code](<https://devfeed.tech/topics/code.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [analysis](<https://devfeed.tech/tags/analysis.md>), [memory](<https://devfeed.tech/tags/memory.md>), [performance](<https://devfeed.tech/tags/performance.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>)

### AI overview

An analysis of Active Record 5.2 argues that its object allocation and internal overhead can produce substantially higher memory usage and slower performance than raw database access. The article compares several Active Record approaches with a raw SQL implementation using allocation measurements.

### Source excerpt

One of the very noble goals of the Ruby community which is being spearheaded by Matz is the Ruby 3x3 plan. The idea is that using large amounts of modern optimizations we can make Ruby the interpreter 3 times faster. It is an ambitious goal, which is notable and inspiring. This "movement" has triggered quite a lot of interesting experiments in Ruby core, including a just-in-time compiler and action around reducing memory bloat out-of-the-box. If Ruby gets faster and uses less memory, then everyone gets free performance, which is exactly what we all want. A big problem though is that there is only so much magic a faster Ruby can achieve. A faster Ruby is not going to magically fix a "bubble sort" hiding deep in your code. Active Record has tons of internal waste that ought to be addressed which could lead to the vast majority of Ruby applications in the wild getting a lot faster. Rails is the largest consumer of Ruby after all and Rails is underpinned by Active Record. Sadly, Active Record performance has not gotten much better since the days of Rails 2, in fact in quite a few cases it got slower or a lot slower. Active Record is very wasteful I would like to start off with a tiny example: Say I have a typical 30 column table containing Topics. If I run the following, how much will Active Record allocate? a = [] Topic.limit(1000).each do |u| a << u.id end Total allocated: 3835288 bytes (26259 objects) Compare this to an equally inefficient "raw version". sql = -"select * from topics limit 1000" ActiveRecord::Base.connection.raw_connection.async_exec(sql).column_values(0) Total allocated: 8200 bytes (4 objects) This amount of waste is staggering, it translates to a deadly combo: Extreme levels of memory usage and Slower performance But .. that is really bad Active Record! An immediate gut reaction here is that I am "cheating" and writing "slow" Active Record code, and comparing it to mega optimized raw code. One could argue that I should write: a = [] Topic.select(:id

## Managing db schema changes without downtime

DevFeed: [Managing db schema changes without downtime](<https://devfeed.tech/articles/managing-db-schema-changes-without-downtime-41346.md>)

Original publisher: [Read original article](<https://samsaffron.com/archive/2018/03/22/managing-db-schema-changes-without-downtime>)

Author: Sam Saffron

Published: 2018-03-22T06:30:05Z

Content type: article

Language: en

Sources: [Sam Saffron](<https://devfeed.tech/sources/sam-saffron.md>)

Topics: [Database Migration](<https://devfeed.tech/topics/database-migration.md>), [migration](<https://devfeed.tech/topics/migration.md>), [Deployment](<https://devfeed.tech/topics/deployment.md>), [Rails](<https://devfeed.tech/topics/rails.md>), [CI/CD](<https://devfeed.tech/topics/cicd.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [commit](<https://devfeed.tech/tags/commit.md>), [continuous-deployment](<https://devfeed.tech/tags/continuous-deployment.md>), [database](<https://devfeed.tech/tags/database.md>), [deployment](<https://devfeed.tech/tags/deployment.md>), [downtime](<https://devfeed.tech/tags/downtime.md>), [exceptions](<https://devfeed.tech/tags/exceptions.md>), [integration-test](<https://devfeed.tech/tags/integration-test.md>), [outage](<https://devfeed.tech/tags/outage.md>), [schema](<https://devfeed.tech/tags/schema.md>)

### AI overview

This article explains how database schema changes can cause deployment outages, especially when older application instances remain active and ActiveRecord caches schema information. It describes Discourse's use of richer migration logging and deployment patterns to reduce these risks.

### Source excerpt

At Discourse we have always been huge fans of continuous deployment. Every commit we make heads to our continuous integration test suite. If all the tests pass (ui, unit, integration, smoke) we automatically deploy the latest version of our code to https://meta.discourse.org. This pattern and practice we follow allows the thousands of self-installers out there to safely upgrade to the tests-passed version whenever they feel like it. Because we deploy so often we need to take extra care not to have any outages during deployments. One of the most common reasons for outages during application deployment is database schema changes. The problem with schema changes Our current deployment mechanism roughly goes as follows: Migrate database to new schema Bundle up application into a single docker image Push to registry Spin down old instance, pull new instance, spin up new instance (and repeat) If we ever create an incompatible database schema we risk breaking all the old application instances running older versions of our code. In practice, this can lead to tens of minutes of outage! In ActiveRecord the situation is particularly dire cause in production the database schema is cached and any changes in schema that drop or rename columns very quickly risk breaking every query to the affected model raising invalid schema exceptions. Over the years we have introduced various patterns to overcome this problem and enable us to deploy schema changes safely, minimizing outages. Tracking rich information about migrations ActiveRecord has a table called schema_migrations where it stores information about migrations that ran. Unfortunately the amount of data stored in this table is extremely limited, in fact it boils down to: connection.create_table(table_name, id: false) do |t| t.string :version, version_options end The table has a lonely column storing the "version" of migrations that ran. It does not store when the migration ran It does not store how long it took the migration to

## Connecting to Snowflake with Ruby on Rails

DevFeed: [Connecting to Snowflake with Ruby on Rails](<https://devfeed.tech/articles/connecting-to-snowflake-with-ruby-on-rails-28624.md>)

Original publisher: [Read original article](<https://eng.localytics.com/connecting-to-snowflake-with-ruby-on-rails/>)

Author: Kevin Deisz

Published: 2017-06-09T14:53:09Z

Content type: tutorial

Language: en

Sources: [Localytics](<https://devfeed.tech/sources/localytics.md>)

Topics: [Ruby on Rails](<https://devfeed.tech/topics/ruby-on-rails.md>), [API](<https://devfeed.tech/topics/api.md>), [data-processing](<https://devfeed.tech/topics/data-processing.md>), [Cloud](<https://devfeed.tech/topics/cloud.md>), [Databases](<https://devfeed.tech/topics/databases.md>), [SQL](<https://devfeed.tech/topics/sql.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [adapter](<https://devfeed.tech/tags/adapter.md>), [api](<https://devfeed.tech/tags/api.md>), [cloud](<https://devfeed.tech/tags/cloud.md>), [data](<https://devfeed.tech/tags/data.md>), [data-processing](<https://devfeed.tech/tags/data-processing.md>), [open-source](<https://devfeed.tech/tags/open-source.md>), [ruby-on-rails](<https://devfeed.tech/tags/ruby-on-rails.md>), [snowflake](<https://devfeed.tech/tags/snowflake.md>), [sql](<https://devfeed.tech/tags/sql.md>)

### AI overview

A tutorial on connecting a Ruby on Rails API to the Snowflake data warehouse using unixODBC, Snowflake's ODBC driver, and an ActiveRecord adapter. It explains ODBC, DSN configuration, installation, and debugging.

### Source excerpt

At Localytics, one of the tools we use for data processing is the Snowflake data warehouse. We connect to Snowflake in a couple different ways, but our main data retrieval application is a Ruby on Rails API. To accomplish this we use a combination of unixODBC (an open-source implementation

## ODBC and writing your own ActiveRecord adapter

DevFeed: [ODBC and writing your own ActiveRecord adapter](<https://devfeed.tech/articles/odbc-and-writing-your-own-activerecord-adapter-28630.md>)

Original publisher: [Read original article](<https://eng.localytics.com/odbc-and-writing-your-own-activerecord-adapter/>)

Author: Kevin Deisz

Published: 2017-03-07T22:08:02Z

Content type: article

Language: en

Sources: [Localytics](<https://devfeed.tech/sources/localytics.md>)

Topics: [Ruby on Rails](<https://devfeed.tech/topics/ruby-on-rails.md>), [Rails](<https://devfeed.tech/topics/rails.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Object-relational mapping](<https://devfeed.tech/topics/orm.md>), [API](<https://devfeed.tech/topics/api.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [api](<https://devfeed.tech/tags/api.md>), [database](<https://devfeed.tech/tags/database.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [ruby-on-rails](<https://devfeed.tech/tags/ruby-on-rails.md>)

### AI overview

The article describes Localytics' open-source ODBC adapter for ActiveRecord, enabling Ruby on Rails applications to communicate with ODBC-compliant databases. It explains the adapter's role in a Rails API upgrade and recounts its development from an older fork, including support for multiple Rails branches and database environments. The supplied text ends before the account is complete.

### Source excerpt

Today we are open-sourcing our ODBC adapter for ActiveRecord, which allows Ruby on Rails applications to communicate with ODBC-compliant databases. The impetus for this work was an effort to update one of our APIs to run with the latest Rails and ruby. Along the way we released Rails

## How to Diagnose Ruby on Rails N + 1 Query Problems

DevFeed: [How to Diagnose Ruby on Rails N + 1 Query Problems](<https://devfeed.tech/articles/how-to-diagnose-ruby-on-rails-n-1-query-problems-21072.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2016/04/17/how-to-diagnose-ruby-on-rails-n-plus-1-query-problems/>)

Published: 2016-04-17T12:00:00Z

Content type: tutorial

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Query (disambiguation)](<https://devfeed.tech/topics/query.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Database](<https://devfeed.tech/topics/database.md>), [Heroku](<https://devfeed.tech/topics/heroku.md>), [Development](<https://devfeed.tech/topics/development.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [analysis](<https://devfeed.tech/tags/analysis.md>), [database](<https://devfeed.tech/tags/database.md>), [how-to](<https://devfeed.tech/tags/how-to.md>), [performance](<https://devfeed.tech/tags/performance.md>), [production](<https://devfeed.tech/tags/production.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [ruby-on-rails](<https://devfeed.tech/tags/ruby-on-rails.md>)

### AI overview

This tutorial explains how to diagnose Ruby on Rails N + 1 query problems that may be hidden in development but become visible under production traffic. It uses New Relic, including its Heroku add-on, as the primary diagnostic tool and also discusses analyzing application log files. The example demonstrates an application whose controller and view access users, posts, and themes through ActiveRecord, producing more database queries than necessary.

### Source excerpt

Diagnosing performance problems in a production Ruby on Rails application can be deceptively complex. When constructing a new application or expanding the features of an existing one, development environments that are not subject to typical production web traffic may not make performance issues evident. In those instances, the use of some simple (and mostly free) tools can help diagnose performance issues in production. If an application is hosted on Heroku, the New Relic add-on can be added to the application for free. Despite it having a few limitations, the free version of New Relic can be extremely valuable for diagnosing some common performance issues. New Relic will be the primary tool used in this post for analysis, but an application's log files can prove to be just as valuable when analyzed correctly. Setup The example application has the following database structure and respective models: create_table :users do |t| t.string :email t.string :first_name t.string :last_name t.timestamps(null: false) end create_table :posts do |t| t.integer :user_id t.integer :theme_id t.string :content t.timestamps(null: false) end create_table :themes do |t| t.string :name t.timestamps(null: false) end class User < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :user belongs_to :theme end class Theme < ActiveRecord::Base end An example controller, home_controller.rb has a single action: class HomeController < ApplicationController def show @user = User.find(params[:user_id]) end end The above action renders a single simple view, show.html.haml: %h3= "Posts from #{ @user.first_name } #{ @user.last_name }" - @user.posts.each do |post| .theme= "Theme #{ post.theme.name }" .content= post.content Additionally in the application's Gemfile, the New Relic Ruby gem has been added: source 'https://rubygems.org' # ... gem 'newrelic_rpm' On a development machine under no contention, this action will quickly render a page consisting of a User's name inf

## Five More Active Record Features You Should Be Using

DevFeed: [Five More Active Record Features You Should Be Using](<https://devfeed.tech/articles/five-more-active-record-features-you-should-be-using-21069.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2016/03/27/five-more-active-record-features-you-should-be-using/>)

Published: 2016-03-27T12:00:00Z

Content type: tutorial

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Databases](<https://devfeed.tech/topics/databases.md>), [Code](<https://devfeed.tech/topics/code.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [code](<https://devfeed.tech/tags/code.md>), [databases](<https://devfeed.tech/tags/databases.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [ruby-on-rails](<https://devfeed.tech/tags/ruby-on-rails.md>)

### AI overview

This tutorial presents additional ActiveRecord features for Ruby on Rails applications. It explains how pluck can reduce memory allocation when retrieving selected columns, how transactions can preserve atomic behavior when updates fail, and begins discussing model callbacks. The supplied article is truncated during the callbacks section.

### Source excerpt

In a previous post, I illustrated a few helpful ActiveRecord features. The entire API of ActiveRecord cannot possibly be contained within a single or even a handful of digestible posts; but, here are at least five more pieces of that massive API that some might find useful. Just like before, the example application used to demonstrate these features will be an imaginary Ruby on Rails application: "booksandreviews.com": class Book < ActiveRecord::Base belongs_to :author has_many :reviews end class Author < ActiveRecord::Base has_many :books end class Review < ActiveRecord::Base belongs_to :book end 1. pluck Introduced in Ruby on Rails 4.0, the pluck method helps keep memory allocation to a minimum when returning results from ActiveRecord queries. A great use case for the pluck method is when a database table backing an ActiveRecord object has a very large number of columns. In this situation, returning an object's full dataset can be cause unnecessary memory allocation and potentially expensive deserialization (in the case of custom or JSON serialized columns). To get a list of book_ids from the 'fantasy' genre, the pluck method is a simple to use: Book.where(genre: 'fantasy').pluck(:id) # SELECT "books"."id" FROM "books" WHERE "books"."genre" = 'fantasy' => [1, 3, 45, ...] An important thing to recognize about the pluck method is its return value. Unlike its cousin, select, the pluck method does not return an ActiveRecord instance. Multiple column names may be passed to pluck and the values of these columns will be returned in a nested Array. The returned Array will maintain the order of columns to how they were requested: Book.where(genre: 'fantasy').pluck(:id, :title) # SELECT "books"."id", "books"."title" FROM "books" WHERE "books"."genre" = 'fantasy' => [[1, 'A Title'], [3, 'Another One']] While possible, it might not always be the best idea to request multiple columns in a single pluck call. Too many columns can produce an unruly result and nullify the performa

## The Power of Arel

DevFeed: [The Power of Arel](<https://devfeed.tech/articles/the-power-of-arel-21067.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2016/03/13/the-power-of-arel/>)

Published: 2016-03-13T12:00:00Z

Content type: tutorial

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Object-relational mapping](<https://devfeed.tech/topics/orm.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [SQL](<https://devfeed.tech/topics/sql.md>), [Databases](<https://devfeed.tech/topics/databases.md>), [web applications](<https://devfeed.tech/topics/web-applications.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [orm](<https://devfeed.tech/tags/orm.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [ruby-on-rails](<https://devfeed.tech/tags/ruby-on-rails.md>), [sql](<https://devfeed.tech/tags/sql.md>), [web-applications](<https://devfeed.tech/tags/web-applications.md>)

### AI overview

This tutorial explains how Arel, the relational algebra library underlying ActiveRecord, helps Ruby on Rails developers construct complex database queries in pure Ruby. It compares Arel-based query composition with raw SQL, including filtering by dates and disambiguating columns when joining tables.

### Source excerpt

Many modern web applications have at least a few overlapping responsibilities. One of these responsibilities deals with maintaining state. A common choice for storing this state is by way of a relational database. Ruby on Rails applications assume the presence of a database by default and communicate with it via ActiveRecord. ActiveRecord is an Object Relational Mapping (ORM). Under the hood, ActiveRecord uses a relational algebra library called Arel to compose queries for execution. Arel is a very powerful library readily available for when ActiveRecord falls short. The Basics Keeping up with tradition, assume a standard Ruby on Rails application exists with at least two models, User and Post: create_table "posts" do |t| t.integer "user_id" t.string "category" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "users" do |t| t.string "first_name" t.string "last_name" t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false end class User < ActiveRecord::Base has_many :posts end class Post < ActiveRecord::Base belongs_to :user end Ask: Find all posts within a category belonging to a user. For such a simple query, ActiveRecord is capable of generating the appropriate SQL statement: Post.where(user_id: 123, category: 'news') .to_sql # => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" = 123 AND "posts"."category" = 'news' However, if the query needed to be more complex, this simple where clause is not sufficient. For example, instead of all posts within a category for a user, only the posts which have a created_at in the current month are desired. A naive ActiveRecord only solution might look like: beginning_of_month = Date.today .beginning_of_month Post.where(user_id: 123, category: 'news') .where('created_at >= ?', beginning_of_month) .to_sql # => SELECT "posts".* FROM "posts" WHERE "posts"."user_id" = 123 AND "posts"."category" = 'news' AND (created_at >= '2016-03-01' ) This query will

## Ruby Threads and ActiveRecord Connections

DevFeed: [Ruby Threads and ActiveRecord Connections](<https://devfeed.tech/articles/ruby-threads-and-activerecord-connections-21063.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2016/02/14/ruby-threads-and-active-record-connections/>)

Published: 2016-02-14T12:00:00Z

Content type: tutorial

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Ruby](<https://devfeed.tech/topics/ruby.md>), [Concurrent Programming](<https://devfeed.tech/topics/concurrent-programming.md>), [Concurrency](<https://devfeed.tech/topics/concurrency.md>), [Database](<https://devfeed.tech/topics/database.md>), [API](<https://devfeed.tech/topics/api.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [api](<https://devfeed.tech/tags/api.md>), [concurrent-programming](<https://devfeed.tech/tags/concurrent-programming.md>), [database](<https://devfeed.tech/tags/database.md>), [ruby](<https://devfeed.tech/tags/ruby.md>)

### AI overview

This article explains how Ruby threads can process large datasets concurrently while sharing memory within a process. Using ActiveRecord, it demonstrates batched email validation through an external API and discusses the accumulation of database connections created by spawned threads.

### Source excerpt

Processing large data sets is a common problem faced by many production web applications. One solution is to divide the work amongst multiple processes and have each responsible for a single or significantly smaller batch of data. However, this solution is not without its problems. Machine provisioning limitations or financial barriers may invalidate this solution for a very large N. Within the same vein as "divide and conquer" exists another solution, one which requires far fewer parallel processes: Threads. In the Ruby programming language, a Thread is a built-in object for concurrent programming. Unlike independent processes, all Ruby Threads within the same process share memory, enabling each individual Thread to consume or process objects and elements from the same data store. For this example, a database will be queried, results manipulated and finally returned to same database via ActiveRecord. First Pass Given a User model backed by a simple users table: class User < ActiveRecord::Base end class CreateUsersTable < ActiveRecord::Migration def change create_table :users do |t| t.string :first_name t.string :last_name t.string :email t.boolean :validated, default: false t.timestamps null: false end end end The problem to solve is fairly straight forward: All User records that are not already validated should be fetched and an external API hit with their email address for validation, then saved. If a User's email address is not valid, it should be removed. Fast forwarding through time, it can be assumed that a completely serial solution has been written and deemed unsatisfactory. Then, during a second iteration, a bit of concurrent code was written: class UserEmailValidator def self.run User.where(validated: false) .find_in_batches(batch_size: 30) do |user_batch| validate_emails(user_batch) end end def self.validate_emails(user_batch) threads = user_batch.map do |user| Thread.new do email_validator = EmailService.new(user.email) email_validator.validate user.ema

## How to Remove a Column with Zero Downtime in Ruby on Rails

DevFeed: [How to Remove a Column with Zero Downtime in Ruby on Rails](<https://devfeed.tech/articles/how-to-remove-a-column-with-zero-downtime-in-ruby-on-rails-21062.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2016/02/07/how-to-remove-a-column-with-zero-downtime-in-ruby-on-rails/>)

Published: 2016-02-07T12:00:00Z

Content type: tutorial

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Ruby](<https://devfeed.tech/topics/ruby.md>), [Object-relational mapping](<https://devfeed.tech/topics/orm.md>), [Database](<https://devfeed.tech/topics/database.md>), [Persistence](<https://devfeed.tech/topics/persistence.md>), [PostgreSQL](<https://devfeed.tech/topics/postgresql.md>), [Deployment](<https://devfeed.tech/topics/deployment.md>), [Continuous integration](<https://devfeed.tech/topics/continuous-integration.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [continuous-deployment](<https://devfeed.tech/tags/continuous-deployment.md>), [continuous-integration](<https://devfeed.tech/tags/continuous-integration.md>), [database](<https://devfeed.tech/tags/database.md>), [how-to](<https://devfeed.tech/tags/how-to.md>), [orm](<https://devfeed.tech/tags/orm.md>), [postgresql](<https://devfeed.tech/tags/postgresql.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [ruby-on-rails](<https://devfeed.tech/tags/ruby-on-rails.md>), [uptime](<https://devfeed.tech/tags/uptime.md>)

### AI overview

A tutorial explains how removing a database column affected production Ruby on Rails applications before Ruby on Rails 4.0.0, focusing on ORM behavior, uptime, and the multi-phase deployment process used to avoid downtime.

### Source excerpt

For a production Ruby on Rails application, uptime is paramount. Altering the structure of an application's persistence layer is an operation that competes directly with uptime. Specifically, removing a table column within a relational database causes issues with the ActiveRecord ORM (the default relational mapping within a Ruby on Rails application). However, this particular pain point has been removed as of Ruby on Rails 4.0.0, saving developers a lot of headache and greatly reducing the need for structural change coordination. Old and Busted To demonstrate the problem, a simple Ruby on Rails 3.2 application is created with a User model: class User < ActiveRecord::Base end Supporting the User model is a PostgreSQL database table created with a migration: class CreateUsers < ActiveRecord::Migration def change create_table :users do |t| t.string :first_name t.string :last_name t.string :email t.timestamps null: false end end end To ensure this application has as close to 100% uptime as possible, it can be assumed that it is behind some kind of pre-loader. As in, when code is deployed, existing requests are given time to complete before new requests are shepherded over to the new version of the code. In a Ruby on Rails 3.2 application, a problem will arise when a column is removed from the database and the ORM does not have time to restart. In this case, even the pre-loader will not save an application from throwing an error about the missing column. To emulate this problem, a rails console is run in the production environment and a User is created: RACK_ENV=production rails console > User.create(first_name: 'test', last_name: 'test') # => #<User id: 1, first_name: "test", last_name: "test", email nil, created_at: "2016-02-07 21:03:26", updated_at: "2016-02-07 21:03:26"> In parallel, the psql command line client is used to connect to the same production database used by this server, all still running locally. Within this psql prompt, the email column from the users t

## Introduction to Rails 5 Attributes

DevFeed: [Introduction to Rails 5 Attributes](<https://devfeed.tech/articles/introduction-to-rails-5-attributes-21055.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2015/12/20/rails-5-attributes/>)

Published: 2015-12-20T12:00:00Z

Content type: article

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Rails](<https://devfeed.tech/topics/rails.md>), [Persistence](<https://devfeed.tech/topics/persistence.md>), [Code](<https://devfeed.tech/topics/code.md>), [Transactions](<https://devfeed.tech/topics/transactions.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [migration](<https://devfeed.tech/tags/migration.md>), [persistence](<https://devfeed.tech/tags/persistence.md>), [rails](<https://devfeed.tech/tags/rails.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [ruby-on-rails](<https://devfeed.tech/tags/ruby-on-rails.md>), [sql](<https://devfeed.tech/tags/sql.md>), [transactions](<https://devfeed.tech/tags/transactions.md>)

### AI overview

This article introduces ActiveRecord Attributes in Rails 5. The feature lets developers declare an attribute's type and optional default value, providing explicit type coercion for model attributes. The article demonstrates converting a string-backed success field to a boolean without changing a large database column, and discusses using typed attributes for both persisted and object-lifecycle data.

### Source excerpt

Shortly after the tenth anniversary of Ruby on Rails 1.0, Rails 5.0 Beta has been announced. While the main character of this release was without a doubt ActionCable, other really great features have made their debut. Types of Changes One feature that particularly stood out is the introduction of ActiveRecord Attributes. This feature allows a developer to assert a specific type for a given attribute and an optional default value. It is not strict type validation (which I have a very strong affinity for), but it does define explicit type coercion that can be very useful. Given an example application that deals with Transactions, a single table and model might exist: class CreateTransactions < ActiveRecord::Migration def change create_table :transactions do |t| t.integer :user_id t.string :item_name t.integer :quantity t.string :success t.decimal :price t.timestamps(null: false) end end end class Transaction < ActiveRecord::Base end This structure, like most in the wild, could have been created before all edge cases were thought through. For some reason, success is a String instead of a Boolean. While this problem might seem trivial, imagine a system where hundreds of millions of transactions exist. In such a system the entire column might not be able to change without incurring downtime. This is a perfect example problem that Attributes can help remedy. Starting simple, a single line can be added to the Transaction class definition to coerce success to a boolean: class Transaction < ActiveRecord::Base attribute :success, :boolean end Using the same logic that ActiveRecord uses for database column coercion, we can see attributes in action! transaction = Transaction.new(success: 'yes') transaction.success # => true transaction = Transaction.new(success: 'f') transaction.success # => false transaction = Transaction.new(success: 0) transaction.success # => false Just like that, the schema has been improved. Aside from raw SQL update statements, this code now prevents str

## Validates Type 2.0

DevFeed: [Validates Type 2.0](<https://devfeed.tech/articles/validates-type-2-0-21052.md>)

Original publisher: [Read original article](<https://jakeyesbeck.com/2015/11/29/updated-validates-type/>)

Published: 2015-11-29T12:00:00Z

Content type: article

Language: en

Sources: [Jake Yesbeck](<https://devfeed.tech/sources/jake-yesbeck.md>)

Topics: [Ruby](<https://devfeed.tech/topics/ruby.md>), [Library](<https://devfeed.tech/topics/library.md>), [Databases](<https://devfeed.tech/topics/databases.md>)

Tags: [activerecord](<https://devfeed.tech/tags/activerecord.md>), [book](<https://devfeed.tech/tags/book.md>), [information](<https://devfeed.tech/tags/information.md>), [library](<https://devfeed.tech/tags/library.md>), [ruby](<https://devfeed.tech/tags/ruby.md>), [serialization](<https://devfeed.tech/tags/serialization.md>), [validation](<https://devfeed.tech/tags/validation.md>)

### AI overview

The article introduces Validates Type 2.0, a Ruby gem that validates whether values exactly match expected types. The update expands validation from basic Ruby types to any defined system type and adds greater flexibility for serialized attributes, including use cases involving ActiveRecord models and legacy database columns.

### Source excerpt

One of the first projects that I worked on during this Year of Commits was validates_type. In case that name is too obscure, validates_type is a gem for validating that a specific value is exactly the type it is expected to be. The validates_type library is compatible to ActiveModel style validations. Originally, the validates_type gem was very strict with what it validated against. It started with basic included Ruby types like Integer, Float, and String. This was a fine first step but proved too restrictive for basically any use case. In a recent update, the validates_type gem has been extended to validate against any defined type in a system. With this update, the uses of this gem greatly increased. They increased so much that it is possible more than 2 people will use it, and that would be pretty awesome. Still Valid The validates_type gem can be useful for a system that cares about exact types at save time. For instance, a model that has an incorrect database column type (because of legacy or other reasons) can still control validation over its data just the same. If a "junior developer who is now somehow the CTO" created the original system. And if that developer did something like create an is_published column on the authors table set as a varchar, validates_type makes that less of an issue. class Author < ActiveRecord::Base validates_type :is_published, :boolean end If someone tries to assign a nonsense value to the is_published attribute, validates_type will ensure it does not save. Note: callback skipping methods will still save bad values, just like any other ActiveRecord validators. > author = Author.new # => #<Author id: nil, name: nil, created_at: nil, updated_at: nil, is_published: nil> > author.is_published = 'foo' # => "foo" > author.save! # => ActiveRecord::RecordInvalid: Validation failed: is_published is expected to be a Boolean and is not. This way, there is not a bunch of random data in the authors table because of a bad decision made a while a

[Next page](<https://devfeed.tech/tags/activerecord.md?cursor=WyIyMDE1LTExLTI5VDEyOjAwOjAwKzAwOjAwIiwgImM4N2VlMGExLTA1YjItNDI2OS1hMmIyLTM0NmU4ZWVmNzZiYyJd>)