Today I Learned

hashrocket A Hashrocket project

283 posts about #rails surprise

ActiveRecord allows you to view saved changes

Say you have an Activerecord object that you are making changes to.

user = User.last
user.update(first_name: "Joe", last_name: "Hashrocket")

With ActiveModel's Dirty module, you can view the changes made to the model even after it has been saved using the saved_changes method

user.saved_changes
# {"first_name"=>[nil, "Joe"], "last_name"=>[nil, "Hashrocket"]]}

Create Accessors for JSONB column data in Rails

I was recently reading about the ActiveRecord::Store API and just today, I got the chance to use it. It's a really great API for working with serialized data in Rails.

Let's consider the following model Geolocation, with a jsonb column data. The contents of the data column look something like this -

{
  "coordinates": {
    "latitude": "5.887692972524717",
    "longitude": "-162.08234016158394"
  }
}

The store_accessor creates getters and settings for coordinates.

class Geolocation < ApplicationRecord
  store_accessor :data, :coordinates
end

Geolocation.last.coordinates
# => {"latitude" => "5.887692972524717", "longitude" => "-162.08234016158394"}

In my case, I have nested data that I'd like to create accessors for - latitude and longitude. From what I could find, this API doesn't support nested data yet, so we have to bring in a helper from ActiveModel::Attributes. We declare the coordinates portion as a jsonb attribute.

class Geolocation < ApplicationRecord
  store_accessor :data, :coordinates
  store_accessor :coordinates, :latitude, :longitude
  attribute :coordinates, :jsonb
end

geo = Geolocation.new
geo.coordinates
# => nil
geo.latitude
# => nil
geo.longitude
# => nil

geo.latitude = 5.887692972524717
# => 5.887692972524717
geo.coordinates
# => {"latitude"=>5.887692972524717}
geo.longitude = -162.08234016158394
# => -162.08234016158394
geo.coordinates
# => {"latitude"=>5.887692972524717, "longitude"=>-162.08234016158394}

I_Ran_Out_Of_Words_Hopefully_You_Get_My_Point :)

S/O Vlad & LayeredDesignForRailsApplications

https://devdocs.io/rails~7.1/activerecord/store

Scoped Uniqueness Validation

Let's say you have a blog, with Authors and BlogPosts. A BlogPost has an Author and a title. If we have a requirement that the post titles need to be unique, our model would look something like this:

class Blog < ApplicationRecord
  has_one :author

  validates :title, uniqueness: true
end

Let's say the requirement changes, and the post title needs to be unique to the author (yeah it's convoluted, but let's roll with it). So Ann can author a post titled 'Cool Post', and Bob can also author 'Cool Post', but Ann can't publish another post titled 'Cool Post'.

Conveniently, uniqueness validations can be scoped to a particular attributes. So to satisfy the above, we can update the validation to:

class Blog < ApplicationRecord
  has_one :author

  validates :title, uniqueness: {scope: :author_id}
end

Tell Rails Your Foreign Key is a UUID

Let's say you have a blog with an Author model, and you want to create a blog_posts table. Each post has an author, and you want a foreign key on blog_posts to the Author's id.

class CreateAuthors < ActiveRecord::Migration[7.0]
  def change
    create_table :authors do |t|
      t.string :name
    end
  end
end

class CreateBlogPosts < ActiveRecord::Migration[7.0]
  def change
    create_table :blog_posts do |t|
      t.string :title
      t.text :content
      t.references :author, null: false, foreign_key: true

    end
  end
end

Pretty straightforward, right? But if Author#id is a UUID, you'll probably run into some issues with this migration. Rails by default assumes your table's IDs will be BigInt and if your IDs aren't then you need to specify the type in t.references:

class CreateAuthors < ActiveRecord::Migration[7.0]
  def change
    create_table :authors, id: :uuid do |t|
      t.string :name
    end
  end
end

class CreateBlogPosts < ActiveRecord::Migration[7.0]
  def change
    create_table :blog_posts, id: :uuid do |t|
      t.string :title
      t.text :content
      t.references :author, null: false, foreign_key: true, type: :uuid

    end
  end
end

Disable database management tasks in Rails

If you wish to not have Rails manage migrations, seeds, schema changes, etc, you can add the database_tasks: false to your database.yml. This may be useful if you are "inheriting", sharing a database managed with some other system, or if you are connecting to a readonly database.

production:
  database: hashrocket
  adapter: postgresql
  encoding: unicode
  pool: 5
  database_tasks: false

https://guides.rubyonrails.org/active_record_multiple_databases.html#connecting-to-databases-without-managing-schema-and-migrations

Create Environment Specific Rails Credentials

If you've worked with the rails encrypted credentials system before, you're probably familiar with the command to edit them

bin/rails credentials:edit

This will create(if it doesn't exist config/credentials.yml.enc by way of the RAILS_MASTER_KEY). If you only have this credentials file, the items in this file will be available to all environments of your application.

But you can also create/edit environment specific credentials by specifying an environment. This will similarly create 2 files - config/development.key and config/development.yml.enc.

bin/rails credentials:edit --environment development

Credentials specified in this file will only be available in the development environment

https://edgeguides.rubyonrails.org/security.html#custom-credentials

Use foreign-key like attributes with FactoryBot

An odd issue occurs when trying to use attributes similar to methods you'd expect with Rails ActiveRecord relationships in FactoryBot.

Take a relationship named provider. You would expect the ActiveRecord object to have methods for provider and provider_id.

However, some interesting behavior happens when you legitimately have a reason to have methods with those names, not during an ActiveRecord relationship.

FactoryBot.define do
  factory :widget do
    url { "URL" }
	provider { "PROVIDER_NAME" }
	provider_id { "PROVIDER_ID" }
  end
end

One will get cleared out when providing the attributes for provider and provider_id.

There is a long-running issue regarding this, but for now, this is how I could remedy the situation. Set the methods as transient attributes and merge the attributes during initialization.

FactoryBot.define do
  factory :widget do
    url { "URL" }

    transient do
      provider { "PROVIDER" }
      provider_id { "PROVIDER_ID" }
    end

    initialize_with do
      new(
        attributes.merge(
          provider: provider,
          provider_id: provider_id
        )
      )
    end
  end
end

ActiveRecord Strict Loading in Rails

When using ActiveRecord, lazy loading is the default behavior, where associated records are loaded when accessed. While convenient, this can lead to N+1 query problems, where an unanticipated number of database queries are triggered, potentially degrading performance.

Strict loading is a countermeasure to this issue. When enabled, it enforces the eager loading of associations, meaning all necessary data is loaded upfront in a single query. This approach mitigates the risk of N+1 queries and makes data fetching more efficient and predictable.

Strict loading can be set at various levels:

Globally: Set strict loading for all models by configuring it in the application:

config.active_record.strict_loading_by_default = true

Model Level: Enable strict loading for a specific model:

class Book < ApplicationRecord 
  has_many :chapters, strict_loading: true
end

Association Level: Apply it to specific associations:

has_many :comments, strict_loading: true 

Query Level: Use it on a per-query basis:

User.strict_loading.find(params[:id])

Optional routing segments in Rails

Optional routing segments in Ruby on Rails are a versatile feature in the framework's routing system, allowing for more flexible and dynamic URL structures. These segments are denoted by parentheses and can significantly streamline routing patterns.

For example, a route like:

get 'books(/:genre)', to: 'books#index' 

Here, :genre is an optional segment. This route will match /books and /books/fiction, routing them to the books#index action. The presence or absence of the genre parameter can be used within the controller to tailor the response.

Optional segments are handy for simplifying routes that cater to multiple URL patterns, reducing the need for numerous specific routes. They enhance the flexibility and readability of the code, making the application's URL structure more intuitive and user-friendly.

Touch ActiveRecord::Associations

ActiveRecord::Associations#belongs_to has an option of touch.

If passed true, the associated object will have its updated_at/updated_on attributes set to current time.

You can also pass a symbol, in that case that attribute will be updated with the current time in addition to the updated_at/updated_on

class Comment < ApplicationRecord
  # When a comment is saved/destroyed, its post will
  # update the updated_at/updated_on to the current time
  belongs_to :post, touch: true

  # OR

  # When a comment is saved/destroyed, its post will update both
  # the updated_at/updated_on as well as comment_last_updated_at
  belongs_to :post, touch: :comment_last_updated_at
end

Note: No validations are performed when touching.

saved_changes & previous_changes in Rails

In Ruby on Rails, saved_changes and previous_changes are methods used to track changes in Active Record models. saved_changes is used after an object is saved to the database. It provides a hash of all the attributes changed when persisting an object, including their original and final values. This method helps understand what changes have just persisted. On the other hand, previous_changes is used after an object is saved but before reloading. It holds the same information as saved_changes but becomes available only after the save operation and before the object is reloaded. It is helpful for actions triggered immediately after a save, like callbacks or logging changes.

Both methods are instrumental in tracking attribute changes and responding to them effectively in a Rails application.

Verify current password with has_secure_password

Now with Rails 7.1, has_secure_password can now automatically verify the current password when updating the password. This is useful to check if the user who is trying to update the password, knows the current password:

class User < ActiveRecord::Base
  has_secure_password
end

user = User.new(password: "sekret", password_confirmation: "sekret")
user.save
#=> true

user.update(password: "HAHAHA", password_challenge: "")
#=> false, challenge doesn't authenticate

user.update(password: "updated*sekret", password_challenge: "sekret")
#=> true

ActiveRecord's attribute_in_database method

Wanted to share a method that I learned about today.

ActiveRecord has a handy utility for checking the value of an attribute in the database. These methods are actually on the Dirty module, and as such, are intended to be used when checking during validations or callbacks before saving.

These particular methods will read from the database (as their name implies), instead of using the value currently in memory.

There's 2 different methods to be aware of that you can use like below -

class Invoice < ActiveRecord::Base
  validates :amount, presence: true
end

invoice = Invoice.last
invoice.amount
=> 10.0

invoice.amount = 80.0

invoice.attribute_in_database("amount")
=> 10.0

invoice.amount_in_database
=> 10.0

ActiveRecord::AttributeMethods::Dirty Docs

Health endpoint added by default in Rails 7.1

A newly generated Rails 7.1 app will now add an endpoint to your routes file to act as a heartbeat. You can point to many services or monitoring tools to check for downtime.

get "up" => "rails/health#show", as: :rails_health_check

However, this is just an indicator of the application running. If you want to do anything more advanced, like checking if the database is up... feel free to write your own. Ultimately, this is a great addition and will work in most situations.

Lib folder now auto-loaded again in Rails 7.1

Many years ago, the lib folder was removed from being auto-loaded in Rails. However, in Rails 7.1 it's back.

You can add autoload_lib to your config, and the lib folder will be added to your application's autoload paths. It does accept an ignore argument, which allows you to, of course, ignore folders in lib. When your new project is generated, it will add the assets & tasks folder to be ignored.

config.autoload_lib(ignore: %w(assets tasks))

There is a caveat that autoloading of lib is unavailable for Rails engines.

Pre-defined ActiveStorage variants in Rails 7.1

Rails 7.1 adds the ability to use pre-defined variants when calling preview or representation on an attachment.

class User < ActiveRecord::Base
  has_one_attached :file do |attachable|
    attachable.variant :thumb, resize_to_limit: [100, 100]
  end
end

<%= image_tag user.file.representation(:thumb) %>

Here, we declare a thumb variant that can later be referenced—no need to explicitly express the resize_to_limit directly at the image_tag call.

Column alias for ActiveRecord select in Rails 7.1

Previously, when writing an ActiveRecord select and having the need to add a column alias, you'd have to provide a SQL fragment string like so:

Customer.select("customers.name AS customer_name")

=> SELECT customers.name AS customer_name FROM "customers"

Rails 7.1 added a more robust hash syntax for selects that also allows for column aliasing.

Customer.joins(:orders).select(name: :customer_name)

=> SELECT "customers"."name" AS "customer_name", FROM "customers"

Shorthand syntax for ActiveRecord select Rails 7.1

Using the newly available select syntax in Rails 7.1 we can express a SQL select like so:

Customer.joins(:orders).select(customers: [:name], orders: [:total])

=> SELECT "customers"."name", "orders"."total" FROM "customers" INNER JOIN "orders" ON "orders"."customer_id" = "customers"."id"

There's also some shorthand you can utilize to make it even shorter. We can still add column names as Symbols, as we've always been able to. They will reference the Model the select is being performed on.

Customer.joins(:orders).select(:name, orders: [:total])

=> SELECT "customers"."name", "orders"."total" FROM "customers" INNER JOIN "orders" ON "orders"."customer_id" = "customers"."id"

We removed the need to declare the customers table as it is implied from being called on the Customer relation.

Caveat: since declaring other columns is done via a hash, that must be provided as the last argument. You couldn't say something like .select(:id, orders: [:total], :name).

Hash syntax for ActiveRecord select in Rails 7.1

Previously, when writing an ActiveRecord select and wanted to add columns from anything outside of the model you originated from, you'd have to provide a SQL fragment string like so:

Customer.joins(:orders).select("customers.name, orders.total")

=> SELECT customers.name, orders.total FROM "customers" INNER JOIN "orders" ON "orders"."customer_id" = "customers"."id"

Notice above how we declare columns from the customers table and the orders table.

As of Rails 7.1, you can now stay in the ActiveRecord DSL and provide hash key/values. The query example above can directly be expressed as:

Customer.joins(:orders).select(customers: [:name], orders: [:total])

=> SELECT "customers"."name", "orders"."total" FROM "customers" INNER JOIN "orders" ON "orders"."customer_id" = "customers"."id"

You provide the table names as keys and the column names you want to select as Symbols in an Array.

Also, notice that the selected columns in the query are appropriately quoted vs the SQL fragment above.

Expanded routing info in Rails

When using rails and wanting to know how one of your routes plays out, it's very easy to do a quick cli call to rails routes. This gives an overview of all routes in the app.

> rails routes
Prefix             Verb  URI Pattern             Controller#Action
rails_health_check GET   /up(.:format)           rails/health#show
restaurants        GET   /restaurants(.:format)  restaurants#index {:format=>:json}                      

However if we provide the --expanded flag, we get a more verbose output with also tells you exactly where in the routes file it was declared.

> rails routes --expanded
--[ Route 1 ]--------------------------------------------------------------------
Prefix            | rails_health_check
Verb              | GET
URI               | /up(.:format)
Controller#Action | rails/health#show
Source Location   | config/routes.rb:6
--[ Route 2 ]--------------------------------------------------------------------
Prefix            | restaurants
Verb              | GET
URI               | /restaurants(.:format)
Controller#Action | restaurants#index {:format=>:json}
Source Location   | config/routes.rb:11

This could be exceptionally helpful when breaking up large routing files in Rails

Add a Default Format to Routes in Rails

When routing in Rails

# config/routes.rb

resources :users

sure you can respond to say json by going to the format directly (/users.json). What if you want that to always be the format without requesting it in the url? Normally by default we would get HTML if we declare nothing.

Turns out you can pass a defaults option to your routes with format being one of the things that can be accepted.

# config/routes.rb

resources :users, defaults: {format: :json}

Now requesting /users will render the json response as well as /users.json.

Importing Multiline Strings in Rails Config

Say I have a multiline string for an environment variable

MY_VAR="hi
bye"

If I try to import that in a Rails config yml file, I'm going to have a bad time.

config:
  my_value: <%= ENV.fetch("MY_VAR") %>

If this config file is autoloaded, rails is going to blow up on startup:

YAML syntax error occurred while parsing config.yml. Please note that YAML must be consistently indented using spaces. Tabs are not allowed. Error: (<unknown>): could not find expected ':' while scanning a simple key at line 15 column 1 (Psych::SyntaxError)

This is happening because the ERB output is not writing the line breaks in a way that Psych (ruby YAML parser) knows how to handle. We can use String#dump to return the quoted version of the string to make Psych happy.

"hi
bye".dump

=> "\"hi\\nbye\""

So the resulting config would look like so:

config:
  my_value: <%= ENV.fetch("MY_VAR").dump %>

And then our app can start and in console:

Rails.configuration.config.my_value

=> "hi\nbye"

Conditional link_to

In your Rails view, you can conditionally render links thanks to ActionView::Helper using #link_to_if

<%= link_to_if(current_user.nil?, "Login", login_path) %>

When this condition is true it would output:

<a href="/sessions/new/">Login</a>

When it is false it just outputs the text:

Login

If you want a custom rendering for false values, just pass that into a block:

<%= link_to_if(current_user.nil?, "Login", login_path) do
  link_to("Logout", logout_path)
end %>

NOTE: There is also an inverse link_to_unless method available

Here's the docs if you're interested.

ActiveRecord Query with `and`

ActiveRecord has an and method for querying.

Post.where(id: [1, 2]).and(Post.where(id: [2, 3]))
# SELECT "posts".* FROM "posts" WHERE "posts"."id" IN (1, 2) AND "posts"."id" IN (2, 3)

More likely you'd write that by chaining wheres:

Post.where(id: [1, 2]).where(id: [2, 3])

However, and really shines if you have more complicated querying with nesting of ANDs and ORs:

SELECT "posts".* 
FROM "posts" 
WHERE "posts"."id" IN (1, 2) 
  AND ("posts"."title" = 'title'
    OR "posts"."body" IS NOT NULL)

How would you write this in ActiveRecord? A first pass with where and or doesn't get us what we want:

Post.where(id: [1,2])
  .where(title: 'title')
  .or(Post.where.not(body: nil))

# SELECT "posts".* 
# FROM "posts" 
# WHERE ("posts"."id" IN (1, 2) 
# 	AND "posts"."title" = 'title' 
# 	OR "posts"."body" IS NOT NULL)

Instead of A AND (B OR C) we get A AND B OR C. We can use a well-placed and to get the right grouping of conditions:

Post.where(id: [1,2])
  .and(Post.where(title: 'title')
    .or(Post.where.not(body: nil)))

# SELECT "posts".*
# FROM "posts"
# WHERE "posts"."id" IN (1, 2)
#   AND ("posts"."title" = 'title'
#     OR "posts"."body" IS NOT NULL)

Docs

h/t Craig Hafer

Add partial lookup prefixes in Rails

Utilizing partials in Rails can be super powerful, primarily when you use them in other templates. However, using a partial outside of its intended resource when it contains additional partials can give you a bad day.

# app/views/foos/_foo.html.erb

Foobity doo
<%= render "bar" %>
# app/views/dews/show.html.erb

Dewbie doo
<%= render "foos/foo" %>

After requesting the "dews/show" template, you'll probably find yourself with a disappointing error page saying the "bar" partial cannot be found.

Missing partial dews/_bar, application/_bar

As you can gather, partial lookup is trying to find the "bar" partial in the context it was called from. We declared the "foo" partial explicitly, so it did not error there. Since the "foo" partial calls the "bar" partial internally without being fully qualified, Rails is trying to find where it lives but cannot find it.

We can use a trick to help the template finder out. In your controller, we can define a local_prefixes method and add the prefix where the partial lives.

class DewsController < ApplicationController
  def self.local_prefixes
    super << "foos"
  end
  
  ...
end

Rails can now find the sub-partial once you've added "foos" to the lookup context.

Excluding view templates for Spina resources

When creating a view_template in a Spina CMS Rails app there is an option of exclude_from that will take an array of strings. For any resources included in this array, that view template will not be available to pages of that resource.

Here is an example:

theme.view_templates = [
  {
    # The rest of your view template...
    exclude_from: ["main", "blog_resource"]
  }
]

Note: If you want to exclude templates from being used on main spina pages, you can just exclude from the implicit "main" resource.

Quote a SQL Value in Rails

If you saw my last post about Geocoding, you'll notice that the value passed to the geocode sql function is an address. To properly pass that value, we need to make sure that we quote it for SQL land.

❌ Bad

ActiveRecord::Base.connection.execute(<<~SQL)
  select
    rating
  from geocode('#{address}', 1)
SQL

Passing a mundane address like 100 O'Connel Ave will cause the above to throw an error in the database

But if we use the quote function from ActiveRecord, we properly quote our strings for SQL:

✅ Better

quoted_address = ActiveRecord::Base.connection.quote(address)

ActiveRecord::Base.connection.execute(<<~SQL)
  select
    rating
  from geocode(#{quoted_address}, 1)
SQL

Doing this ensures that we mitigate SQL Injection attacks and we properly account for things like single quotes in our values.

https://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/Quoting.html#method-i-quote

Rails config hosts accepts regular expressions

Imagine you're running your Rails server on an ngrok instance. If you want to access your ngrok instance, you're going to need to add your specific ngrok subdomain to your config hosts.

If you ever restart your ngrok instance and get a new subdomain, you now have to change your config hosts again to match the new one.

Well, not anymore! Because now that you know you can use regular expressions, you can just do this:

Rails.application.config.hosts << /.*\.ngrok\.app/

Technically, if your use-case is just for subdomains, you can just do this:

Rails.application.config.hosts << ".ngrok.app"

But it's still nice to know you can utilize regular expressions if needed!

Comparison Validator Also Validates Presence

In ActiveModel, a comparison validation on an attribute will first perform a presence validation, and return a :blank error if the attribute is missing. So you don't have to explicitly add a presence validation if you're also doing a comparison validation (unless you really really want to (I probably still will)).

class SomeClass
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :some_number

  validates(
    :some_number,
    comparison: {greater_than: 8}
  )
end

If you don't provide some_number you'll get a :blank error, and the comparison validation will not run:

pry(main)> foo = SomeClass.new
pry(main)> foo.valid?; foo.errors.full_messages
=> ["Some number can't be blank"]

But if you do provide some_number, then the comparison validation will run as expected:

pry(main)> bar = SomeClass.new(some_number: 3)
pry(main)> bar.valid?; bar.errors.full_messages
=> ["Some number must be greater than 8"]

Source

Bulk Delete Records in Rails with `delete_by`

I'm sure you're familiar with the Active Record method delete_all . But I recently learned of another method that can used to shorthand this method-call on a where statement.

You see - delete_by(...) is the shorthand for Model.where(...).delete_all

Model.where(foo: true, bar: false).delete_all

# vs.

Model.delete_by(foo: true, bar: false)

Similarly to delete_all, you will need to be careful with delete_by as it creates a single delete statement for the database and callbacks are not called.

Bonus round -> destroy_by is a similar shorthand for Model.where(...).destroy

https://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-delete_by

Upload Active Storage Attachments to Specific Path

If you've ever wanted to organize your bucket while using Active Storage, it looks like this is now possible as of Rails 6.1

By passing the key argument to #attach, you can specify the location of the file within the bucket -

class Invoice < ApplicationRecord
  has_one_attached :document
end

invoice = Invoice.create
invoice.document.attach(
  key: "invoices/invoice_1_20230505.pdf",
  io: File.read("invoice_1.pdf")
)

https://github.com/rails/rails/commit/4dba136c83cc808282625c0d5b195ce5e0bbaa68 https://github.com/rails/rails/issues/32790

You can turn arrays into sentences!

There's a neat little method Array#to_sentence that turns your array into a string in sentence format.

It's pretty self-explanatory, so here are some examples:

superheroes = ["Spider-Man", "Batman", "Iron man", "Wonder woman"]

superheroes.to_sentence
=> "Spider-Man, Batman, Iron man, and Wonder woman"

superheroes.to_sentence(
  words_connector: " or ", 
  last_word_connector: " or maybe even "
)
=> "Spider-Man or Batman or Iron man or maybe even Wonder woman"

With slight configuration, you can even have this work in different locales. Check it out in the docs!

Disable "Try it out" feature of Swagger UI

Swagger UI is a great way to view API documentation. It's even got a cool feature where you can excercise the api right from the documentation.

However that may not be wanted or necessary in every occasion. Turning it off wasn't as straightforward as I'd have expected.

The Swagger UI documentation shows a configuration option called tryItOutEnabled. This sounds promising and the description even states:

Controls whether the "Try it out" section should be enabled by default.

So using our knowledge on how to configure Swagger UI through rswag, we try:

Rswag::Ui.configure do |c|
  c.config_object["tryItOutEnabled"] = false
end

However we'll find that this doesn't do anything 😕

Later I found that this particular option sets whether or not the "Try it out" feature is open by default.

If we utilize the config option of supportedSubmitMethods and provide an empty array, we'll get something more usable.

Rswag::Ui.configure do |c|
  c.config_object["supportedSubmitMethods"] = []
end

Now the button will completely disappear!

Configure Swagger UI when using rubygem rswag

The swagger documentation gem rswag contains the library Swagger UI. This allows your generated documentation to be viewable from your webserver.

It's great out of the box but is also more configurable than the gem's documentation would lead you to believe.

You have direct access to things like authentication but anything deeper than that can be controlled via a configuation object.

Rswag::Ui.configure do |c|
  c.config_object["showExtensions"] = true
end

Utilize the configuration's config_object. It is just a hash that you can set with keys that match available options found in Swagger UI's configuration docs

Custom Flash Messages in Rails

Why Aren't My Flash Messages Working?

Turns out, there's 2 keys that Rails supports by default for flash messages. Those are alert and notice; you can use them like this in your controller:

redirect_to users_path, notice: "User created successfully"
# - or -
render :new, alert: "An error prevented the user from being saved"

But if your flash rendering code is generic enough, you might notice that explicitly setting a key/message on flash will work for values other than the defaults:

flash[:success] = "User created successfully"
redirect_to users_path

TIL Rails has a helper that will allow us to add our own custom flash messages - add_flash_type. You can use this an a controller (re: ApplicationController) to enable new flash message types. This will allow you to do the one liners in render and redirect calls:

class ApplicationController < ActionController::Base
  add_flash_type :my_flash_type
end

# ...

redirect_to users_path, my_flash_type: "User created successfully"
# - or -
render :new, my_flash_type: "An error prevented the user from being saved"

In addition, it will also add a variable in our views to retrieve this message:

<%= my_flash_type %>

https://api.rubyonrails.org/classes/ActionController/Flash/ClassMethods.html

Disable strong parameters in rails

⚠️ Don't do thisYou should never do this. This was used for a non-public internal active admin application that needed to be updated. This app was not intended for public use. Please don't do this.
# config/environments/development.rb
require "active_support/core_ext/integer/time"

Rails.application.configure do
  config.action_controller.permit_all_parameters = true
end

Setting the url_options hash in the controller

When grabbing the url of an ActiveStorage record through any of these methods: ActiveStorage::Blob#url,ActiveStorage::Variant#url,ActiveStorage::Preview#url you may find yourself running into this error:

Cannot generate URL for <FILENAME> using Disk service, 
please set ActiveStorage::Current.url_options.

This can be resolved in the controller by utilizing a concern that ActiveStorage provides for us; ActiveStorage::SetCurrent.

It would look like this in your controller:

class MyController < ApplicationController
  include ActiveStorage::SetCurrent
  
  # The rest of your controller...
end

And now whenever you go to call #url on your ActiveStorage record, it will know where to generate the url from!


Including ActiveStorage::SetCurrent sets the ActiveStorage::Current.url_options hash to match the current request.

Rails' .insert_all method is too naive

Rails requires a unique index in order to use the .insert_all methods. This requirement can make this method very brittle and unusable. If your conflict target is the table's primary key, this won't work unless you create a redundant index on the table for this method to match against. This creates an amazing amount of waste not only of storage space, but also performance. This method would allow so many more use cases if it simply let you describe the conflict you want to match against.

More advanced method:

class ApplicationRecord
  def self.bulk_insert(array_of_hashes, conflict_targets = Array(primary_key))
    columns = array_of_hashes.first.keys
    values = array_of_hashes.flat_map(&:values)
    rows = array_of_hashes.map do |f|
      "(#{columns.size.times.map { "?" }.join(", ")})"
    end.join(", ")

    sql = sanitize_sql_array([<<~SQL, *values])
      INSERT INTO "#{table_name}"
      (#{columns.map { |c| "\"#{c}\"" }.join(",")})
      VALUES #{rows}
      ON CONFLICT (#{conflict_targets.map { |c| "\"#{c}\"" }.join(", ")}) DO NOTHING
    SQL

    connection.execute(sql.squish)
  end
end

SQL it produces:

User.bulk_insert([{email: "a@example.com"}, {email: "b@example.com"}])
INSERT INTO "users" ("email") VALUES ('a@example.com'), ('b@example.com') ON CONFLICT ("id") DO NOTHING

This would then allow you to reference any conflict you like:

alter table users add unique (email);
User.bulk_insert(
  [{email: "a@example.com"}, {email: "b@example.com"}],
  %i[email]
)

Direct many-to-many ActiveRecord associations

By using has_and_belongs_to_many you can directly relate models with a many-to-many-association. For example, if you have a model Film and a model Producer, a film can have multiple :producers, and a Producer can have multiple :films; in this case, each of models could have a has_and_belongs_to_many association with the other.

#film.rb
class Film < ApplicationRecord
  has_and_belongs_to_many :producers
end

#producer.rb
class Producer < ApplicationRecord
  has_and_belongs_to_many :films
end
# Now associative records can be stored and retrieved
film = Film.where(title: "The Irishman")
producer = Producer.where(name: "Martin Scorcese")
film.producers << producer
film.save

producer.films
#=> This should return a collection including The Irishman
films.producers
#=> This should return a collection including Martin Scorcese

Confirmation alert using Turbo in Rails

Using an confirmation browser alert is a common thing to do. This seemingly works fine while using Turbo, however, try to cancel the alert and your request still goes through.

Previously on rails:

<%= link_to "Go away", "/go-away", data: {confirm: "Are you sure?"} %>

Use data-turbo-confirm for correct functionality:

<%= link_to "Go away", "/go-away", data: {turbo_confirm: "Are you sure?"} %>

The Outlet of Rails Stimulus

Besides values and targets Rails Stimulus has now outlets. Now we can invoke functions from one controller to the other like that:

// result_controller.js
export default class extends Controller {
  markAsSelected(event) {
    // ...
  }
}
// search_controller.js
export default class extends Controller {
  static outlets = [ "result" ]

  selectAll(event) {
    this.resultOutlets.forEach(result => result.markAsSelected(event))
  }