如何为Rails Apartment定义种子文件

3

我已经设置了模式文件,但是无法为租户定义种子文件,以便它仅在租户迁移时运行。此外,我正在尝试在创建用户并创建其租户后创建模式。

    require 'apartment/elevators/subdomain'

    #
    # Apartment Configuration
    #
    Apartment.configure do |config|

      config.excluded_models = ["Admin","Contractor", "ContractorPackage","ContractorTransaction","Country","Currency","Faq","FaqCategory","Language","Package","Page","PaymentType","Setting","TempTransaction","Testimonial","Timezone","Tutorial"]

      # use postgres schemas?
      config.use_schemas = true

       config.tenant_names = lambda{ Contractor.pluck("CONCAT('contractor_',id)") }
    end

    # overriding module schema file here
    module Apartment

      class << self
            def database_schema_file
                @database_schema_file=Rails.root.join('db', 'contractor_schema.rb')
            end
        end

    end


    Rails.application.config.middleware.use 'Apartment::Elevators::Subdomain'

Rake db:seed 将会完成它。 - Dinesh Saini
它将为公共模式进行种子处理。我只想运行用户/租户。 - user3226960
这里有很多代码,大部分都是注释;你能否清除注释,简化你所呈现的内容,并将代码限制在直接涉及问题的范围内(可能是这里的所有代码)。 - rfornal
你能让它正常工作了吗? - rdubya
1个回答

17
在你的seeds.rb文件中,将代码包含在对当前租户的检查中。我现在没有地方测试这个,但是以下代码应该可以让你接近目标:

在你的seeds.rb文件中,将代码包含在对当前租户的检查中。我现在没有地方测试这个,但是以下代码应该可以让你接近目标:

unless Apartment::Tenant.current == 'public'
    #Insert seed data
end
如果你想手动种植一个租户,你应该能够运行Apartment::Tenant.seed
要在创建租户时运行seeds.rb文件,请添加:
config.seed_after_create = true

到您的公寓初始化文件。

以您的示例为例:

Apartment.configure do |config|

  config.excluded_models = ["Admin","Contractor", "ContractorPackage","ContractorTransaction","Country","Currency","Faq","FaqCategory","Language","Package","Page","PaymentType","Setting","TempTransaction","Testimonial","Timezone","Tutorial"]

  # use postgres schemas?
  config.use_schemas = true

  config.tenant_names = lambda{ Contractor.pluck("CONCAT('contractor_',id)") }

  config.seed_after_create = true
end

1
但是我们如何从模型中运行种子命令呢?假设在用户模块中有一个名为after_create的函数:create_schema def create_schema

创建租户命令

>> 在这里如何运行seed命令?????

end
- Dinesh Saini
1
刚刚添加了关于如何做到这一点的信息。 - rdubya
你能否在问题中添加实际的错误信息以及导致错误的相关代码? - rdubya
@rdubya的回答完全有效。但我需要更多的东西,比如在后台运行种子。因为我需要用所有国家及其州和其他一些东西来播种。它几乎需要3分钟才能完成种子,用户在所有种子完成之前不会收到通知。所以我需要在后台运行它。有什么建议吗? - thedudecodes
正确的写法应该是 unless Apartment::Tenant.current == 'public'(跳过 _tenant)。 - Marek Dlugos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接