ruby-on-rails Ruby on Rails使用“循环”引用的Rails模型

6tqwzwtp  于 2022-11-19  发布在  Ruby
关注(0)|答案(1)|浏览(214)

我正在尝试创建一个基础模型“客户端”:

class CreateClients < ActiveRecord::Migration[7.0]
  def change
    create_table :clients do |t|
      t.string :name

      t.timestamps
    end
  end
end

客户端具有审核列表:

class CreateAudits < ActiveRecord::Migration[7.0]
  def change
    create_table :audits do |t|
      t.references :client, null: false, foreign_key: true

      t.timestamps
    end
  end
end

每个客户都有一个审计列表。这部分很简单。我有点不确定的是如何处理将客户添加到每个审计中。我的意思是...客户有一个名称,每年左右我们希望允许审计发生,客户可以查看他们的每个字段并进行更改,通过审批流程,然后最终更改客户属性。
我希望审核“have_a”客户端,以便在将审核更改推回基本客户端并关闭审核之前跟踪对客户端的更改。
它应该看起来像这样:
第一次
我一直收到错误消息:

➜  project_rails git:(main) ✗ rake db:migrate                                      
== 20221028145314 AddClientToAudits: migrating ================================
-- add_reference(:audits, :client, {:null=>false, :foreign_key=>true})
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

you can't define an already defined column 'client_id'.

如何创建审计的子客户端?

  • 编辑-
    阐述:
    一种解决方案是在审计中保留与客户端相同的属性。但是,当他们向客户端添加地址时,必须记住,然后再向审计添加一个具有完全相同名称的地址。这就是为什么我尝试重用客户端对象--添加到客户端的任何属性都会自动添加到审计中。
    也可以接受其他解决方案的想法。
tnkciper

tnkciper1#

如果我没有理解错的话,您的数据库中已经建立了正确的关系。请查看您的structure.sqlschema.rb文件,确认这些关系是否已经正确。另一种确认方法是使用rails console创建垃圾客户端、垃圾审计,并将它们关联起来。然后尝试audit.client_id确认这些关系是否已经存在。
我认为您需要做的是将以下代码添加到Rails模型文件中,以便可以在代码中引用审计中的客户机。
比如:

class Audit < ApplicationRecord
  # other attributes

  belongs_to :client, required: true

  # ...
end

现在您可以说audit.client来进行更新。

相关问题