Context You have an array of hashes and want to check if all elements are satisfying a condition. TIL You might want to do this in Ruby: objects.all? { _1[:amount] > 10 } In th...
Short Ruby or Ruby on Rails tips or Today I Learned moments
Context You have an array of hashes and want to check if all elements are satisfying a condition. TIL You might want to do this in Ruby: objects.all? { _1[:amount] > 10 } In th...
Context You have a column in your table that is used as an array , like this: t.string 'ids', array: true And you want to select all records that have more than N elements i...
Context Let's say that you have two array of hashes: a = [ { initial: "a", email: "a@example.com" }, { email: "b@example.com", initial: "b" }, { ...
Context You want to update the same column for multiple records in one query and set different values for each record. Example: class Car < ActiveRecord::Base # has attributes: ...
Rails 7 introduced a new way to create enums in PostgreSQL, by adding create_enum method. See official documentation here. I will explore the following tasks: Creating an enum ...
How to get the class name To get the class name: class User def call = puts self.class.name end User.new.call #=> User This will work even if the name is namespace inside a m...
If you want to freeze strings in Ruby there are at least two ways to do this: 1) Adding the magic comment at the beginning of the file # frozen_string_literal: true 2) Calling ...
Use ActiveRecord::Suppressor, conditional callbacks, or patch ApplicationRecord to skip Rails callbacks.