Rails mountable engine with isolate_namespace but without prefixed namespace on tables

懵懂的女人 提交于 2020-01-22 13:52:33

问题


Is there a way to configure the isolate_namespace method to not use prefixed table names?

class Engine < ::Rails::Engine
  isolate_namespace MyEngine
end

Additionally, an isolated engine will set its name according to namespace, so MyEngine::Engine.engine_name will be “my_engine”. It will also set MyEngine.table_name_prefix to “my_engine_”, changing the MyEngine::Article model to use the my_engine_articles table.Isolated Engine Docs

When designing a prototype I ran into an issue where I need the routes to use the isolated namespace pattern, but the database tables do not. This is because the mountable engine I am writing has it's own self contained database.

Don't want to dig much further if it's not possible.


回答1:


Rails 3 and 4
Did a little digging into the Rails Engine codebase to find a solution. If you define a method to specify the table name prefix (in /lib/my_engine.rb), it will just use that instead. So set returning nil works fine.

require "my_engine/engine"

module MyEngine
  # Don't have prefix method return anything.
  # This will keep Rails Engine from generating all table prefixes with the engines name
  def self.table_name_prefix
  end
end



回答2:


For Rails 5, the solution seems to be declaring the following on whatever models you want within your engine:

self.table_name = "name_you_want"

This won't affect generation, but accomplishes the use case that the original poster asks about, I think.



来源:https://stackoverflow.com/questions/19435214/rails-mountable-engine-with-isolate-namespace-but-without-prefixed-namespace-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!