我需要在我的Rails应用程序中查看SQL和存储过程,所以我必须从schema.rb更改为structure.sql。这是我在config/application.rb中的配置
config.active_record.schema_format = :sql但是当我在seed.rb中为一个实体创建一个新记录时
Company.create(
name: 'Google',
subdomain: 'google'
)错误发生
my_project/db/schema.rb还不存在
我不知道有什么问题。我是不是漏掉了cofig中的一些东西,有些地方还需要schema.rb,还是漏了一些rake任务命令?我刚用了
rake db:migrate db:test:prepare遵循这个博客https://rietta.com/blog/2013/11/28/rails-and-sql-views-for-a-report/#setting-up-the-sql-view
更新:我正在使用apartment-gem,Company实体是租户。
下面是apartment.rb中的配置
Apartment.configure do |config|
config.excluded_models = %w{ Company CommonField }
config.tenant_names = lambda{ Company.pluck(:subdomain) }
# ==> PostgreSQL only options
config.use_schemas = true
# Apartment can be forced to use raw SQL dumps instead of schema.rb for
# creating new schemas.
# Use this when you are using some extra features in PostgreSQL that can't
# be respresented in
# schema.rb, like materialized views etc. (only applies with use_schemas set
# to true).
# (Note: this option doesn't use db/structure.sql, it creates SQL dump by
# executing pg_dump)
#
# config.use_sql = false
# <== PostgreSQL only options
config.prepend_environment = !Rails.env.production?
end我尝试将config.use_schemas更改为false,然后启用并将config.use_sql设置为true,但仍然无法工作。也许它只是为PosrtgreSQL设置的。
那么,有MySQL的设置吗?
发布于 2021-06-18 17:14:22
gem apartment中的mysql2_adapter从abstract_adapter扩展而来,它继承了创建方法,如下所示:
def create(tenant)
run_callbacks :create do
create_tenant(tenant)
switch(tenant) do
import_database_schema
# Seed data if appropriate
seed_data if Apartment.seed_after_create
yield if block_given?
end
end
end如果没有这样的文件,import_database_schema方法会抛出错误:FileNotFound ... db/schema.rb doesn't exist yet,所以我想当您决定使用structure.sql而不是schema.rb时,您会删除它。
我建议两种方法来解决:
schema.rb,它。use_schemas,因为这表明apartment将使用postgresql schemas和mysql use,但是对于mysql,如果使用structure.sql,则根本不需要import_database_schema,对吗?因此,您可以创建新的mysql适配器,如下所示:# your-app/lib/apartment/adapters/mysql2_structure_adapter.rb
require 'apartment/adapters/mysql2_adapter'
module Apartment
module Tenant
def self.mysql2_adapter(config)
if Apartment.use_schemas
Apartment.use_sql ?
Adapters::Mysql2StructureAdapter.new(config) :
Adapters::Mysql2SchemaAdapter.new(config)
else
Adapters::Mysql2Adapter.new(config)
end
end
end
module Adapters
class Mysql2StructureAdapter < Mysql2SchemaAdapter
def create(tenant)
run_callbacks :create do
create_tenant(tenant)
switch(tenant) do
# no need to import schema
# import_database_schema
# Seed data if appropriate
seed_data if Apartment.seed_after_create
yield if block_given?
end
end
end
end
end
end然后加载该适配器,并在初始化程序配置上同时打开use_schemas和use_sql。
# config/initializers/apartment.rb
Apartment.configure do |config|
# ...
config.use_schemas = true
config.use_sql = true
end
# ...
Dir[File.join(Rails.root, "lib", "apartment", "adapters", "**/*.rb")].each {|r| require r}https://stackoverflow.com/questions/43838706
复制相似问题