具有唯一性条件的 Rails 嵌套形式

发布于 2024-10-26 13:19:41 字数 835 浏览 0 评论 0原文

Rails 2.3.5,Ruby 1.8.7。

我有三个模型:Person、AcademicTerm 和 PersonTermStatus。

class PersonTermStatus {
  belongs_to :academic_term
  belongs_to :person
  validates_uniquness_of :academic_term_id, :scope => :person_id
  @ ...
}

class Person {
  has_many :person_term_statuses
}

在人员记录的动态嵌套表单中,我允许编辑 person_term_statuses。但是,如果用户执行以下任一操作,我会收到验证错误:

  1. 删除状态并在同一更改中创建具有相同学术术语的新状态。
  2. 在两种现有状态之间交换学术术语。

我明白为什么会发生这种情况。在(1)中,在新状态的唯一性条件验证之前,标记为删除的状态并未被实际删除。在(2)中,在任何更改之前再次应用唯一性条件,并且它找到具有相同学术术语的另一条记录。

问题是,我想不出办法解决这个问题。有已知的解决方案吗?

(我的嵌套表单实现目前几乎完全使用 RailsCast 的技术 [ Part我第二部分

Rails 2.3.5, Ruby 1.8.7.

I have three models, Person, AcademicTerm, and PersonTermStatus.

class PersonTermStatus {
  belongs_to :academic_term
  belongs_to :person
  validates_uniquness_of :academic_term_id, :scope => :person_id
  @ ...
}

class Person {
  has_many :person_term_statuses
}

In a dynamic nested form for a Person record, I allow the editing of the person_term_statuses. But I get validation errors if the user does either of the following:

  1. Deletes a status and creates a new one with the same academic term in the same change.
  2. Swaps the academic terms between two existing statuses.

I understand why this is happening. In (1), the status marked for deletion is not actually deleted before validation of the new status's uniquness condition. In (2), the uniquness condition again is applied before any changes, and it finds another record with the same academic_term.

The problem is, I can't figure a way around this. Is there a known solution?

(My nested form implmenetation is currrently using pretty much exactly the technique from RailsCast [ Part I and Part II )

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

天暗了我发光 2024-11-02 13:19:41

据我所知,没有解决方法。但是,您可以将外键添加到数据库中以强制数据库端的唯一性,然后使用以下方法。

将 before_validation 添加到父模型,删除所有子模型并将其重新创建为新记录。然后添加一个自定义验证函数,根据内存中的内容(而不是数据库中的内容)手动检查子记录的唯一性。

这种方法的缺点包括:

  • 孩子们不会保留相同的 ID。
  • 创建的时间戳发生变化。

There is no workaround for this that I know of. However, you can add foreign keys to your database to enforce the uniqueness on the database side and then use the following approach.

Add a before_validation to the parent model that deletes and recreates as new records all the children. Then add a custom validation function that manually checks the children records for uniqueness based on what's in memory (rather than what's in the database).

The downsides to this approach include:

  • The children don't retain the same IDs.
  • The created timestamp changes.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文