具有唯一性条件的 Rails 嵌套形式
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)中,在任何更改之前再次应用唯一性条件,并且它找到具有相同学术术语的另一条记录。
问题是,我想不出办法解决这个问题。有已知的解决方案吗?
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:
- Deletes a status and creates a new one with the same academic term in the same change.
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,没有解决方法。但是,您可以将外键添加到数据库中以强制数据库端的唯一性,然后使用以下方法。
将 before_validation 添加到父模型,删除所有子模型并将其重新创建为新记录。然后添加一个自定义验证函数,根据内存中的内容(而不是数据库中的内容)手动检查子记录的唯一性。
这种方法的缺点包括:
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: