4

I'm currently doing the following which works but is inefficient since it's calling it before every action

class ApplicationController < ActionController::Base
  before_action :set_intervalstyle
  
  private
  def set_intervalstyle
    ActiveRecord::Base.connection.exec_query("SET intervalstyle = iso_8601", "SCHEMA")
  end
end

I noticed here that they're registering this command per connection

  alias_method :configure_connection_without_interval, :configure_connection
  define_method :configure_connection do
    configure_connection_without_interval
    execute('SET intervalstyle = iso_8601', 'SCHEMA')
  end

Could someone help me figure out how to convert my before_action into something like this? Maybe as an initializer? I'm not sure where to start

3
  • Is this something that can be set server-side? I'm not sure Rails can do it for you out of the box. Commented Aug 10, 2020 at 20:10
  • I monkeyed something as an initializer which seems to work but I'm not sure if it's a good idea to override configure_connection require 'active_record/connection_adapters/postgresql_adapter' class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter def configure_connection execute('SET intervalstyle = iso_8601', 'SCHEMA') end end Commented Aug 10, 2020 at 20:56
  • Probably not a great idea, which is why I was asking about server-side settings for defaults like this. Commented Aug 10, 2020 at 21:01

1 Answer 1

3

Not sure if this is a good idea but so far this works and hasn't had any side effects

config/initializers/set_intervalstyle.rb

require 'active_record/connection_adapters/postgresql_adapter'

class ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
  alias_method :configure_connection_without_interval, :configure_connection

  def configure_connection
    configure_connection_without_interval
    execute('SET intervalstyle = iso_8601', 'SCHEMA')
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.