Sharjeel
Sharjeel

Reputation: 15798

Extent ActionText::RichText to override table_name

ActionText::RichText class has table name hard coded in Rails code.

self.table_name = "action_text_rich_texts"

It ignores table_name_prefix setting and makes it not possible to have a table name project_a_action_text_rich_texts work.

Is there a way to override table_name that's coming from Rails class ActionText::RichText?

Update: Updating two apps to Rails 6.x that share the same database in the cloud but use table_name_prefix to have separate set of tables.

In Rails, table names for ActionText and ActiveStorage are hard coded. Goal is to make Project A read project_a_action_text_ and Project B read project_b_action_ tables.

Upvotes: 0

Views: 378

Answers (1)

Sharjeel
Sharjeel

Reputation: 15798

It looks like it will be fixed at least for ActiveStorage in Rails 7

Until then I used the following patch to override table_name in ActionText and ActiveStorage. Make sure to verify it's working (or remove it) when you upgrade Rails to 7.

Here's the example for ActionText

First create a module in lib folder and set new table_name

#lib/extensions/action_text_rich_text.rb
# frozen_string_literal: true
module Extensions::ActionTextRichText
  extend ActiveSupport::Concern

  def table_name
    'project_a_action_text_rich_texts'
  end  
end

Create a new initializer and add extension module to ActionText

#config/initializers/extensions.rb
Rails.application.config.to_prepare do
  ActionText::RichText.extend Extensions::ActionTextRichText    
end

It will override table_name set in Rails ActionText module. Now you can update table name in ActionText migration generated by Rails and run the migration.

You can test by calling ActionText::RichText.table_name in Rails console. It should print new table name that you set in your extension.

Upvotes: 0

Related Questions