【问题标题】:Foreign key issue with apartment gem is there any other solution to insert data in associate table公寓 gem 的外键问题是否有其他解决方案可以在关联表中插入数据
【发布时间】:2017-12-21 14:52:28
【问题描述】:

以下是我从主数据库向关联模型中添加数据时遇到的错误。

ActiveRecord::InvalidForeignKey: PG::ForeignKeyViolation: 错误: 在表“配置”上插入或更新违反外键 约束“fk_rails_29e23e6ceb”详细信息:键(company_id)=(129)是 不存在于表“公司”中。

【问题讨论】:

  • 分享你的模型架构..
  • Company has_many :configurations Configuration belongs_to :company `` 公司模型被排除在租户之外,并且配置模型在租户中```
  • schema 在表列和数据类型中,而不是 associations..
  • ** create_table "configurations", force: :cascade do |t| t.string "key" t.string "value" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "catelog_source_id" t.boolean "visible", 默认: true t.整数“company_id” t.index [“catelog_source_id”],名称:“index_configurations_on_catelog_source_id”,使用::btree t.index [“company_id”],名称:“index_configurations_on_company_id”,使用::btree end
  • This answer 似乎表明这是不可能的。

标签: ruby-on-rails postgresql activerecord apartment-gem


【解决方案1】:

我遇到了同样的问题,并花了很多时间试图找出造成这种情况的原因。 解决方案非常简单(至少在我的情况下)。 直接来自 gem 的文档:

如果您有一些模型应该始终访问“公共”租户, 您可以通过使用配置公寓来指定这一点 公寓。配置。这将为您生成一个配置对象。你可以> 像这样设置排除模型:

config.excluded_models = ["User", "Company"]        # these models
 will not be multi-tenanted, but remain in the global (public)
 namespace  ```

所以只需将它添加到你的 apartment.rb 文件即可。

Apartment.configure do |config|
  config.excluded_models = %w{ User Company }
  ...
end

【讨论】:

    猜你喜欢
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2019-03-26
    • 2021-09-06
    相关资源
    最近更新 更多