是否有可以用于所有关联记录上的特定属性的验证? [英] Is there a validation I can use for a specific attribute on all associated records?

查看:39
本文介绍了是否有可以用于所有关联记录上的特定属性的验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Question has_many :answers(就像 SO).我还希望每个问题只有 1 个 accepted_answer,所以我只是在 Answer 模型中添加了一个 :accepted 属性,它只是一个布尔值.

I have a Question that has_many :answers (just like SO). I also want each question to have only 1 accepted_answer, so I just added an :accepted attribute to the Answer model that is simply a boolean.

现在,为了获得我的问题的公认答案,我在我的模型上编写了一个方法来执行此操作:

So now, to get the accepted answer for my question, I have written a method on my model that just does this:

  def accepted_answer
    answers.where(accepted: true)
  end

这允许我执行 question.accepted_answer 并且它返回一个您期望的 ActiveRelation 对象.

That allows me to do question.accepted_answer and it returns an ActiveRelation object like you would expect.

没什么特别的.简单有效.

Nothing fancy. Simple and effective.

然而,我想确保的是,在任何时候,每个问题都只能有一个accepted: true 的答案.

However, what I want to ensure though is that there can only be one answer on each question that is accepted: true at any moment in time.

解决这个问题的最佳方法是什么?

What's the best way to approach this?

我考虑过使用验证器,但我找不到以这种方式处理关联对象的验证器.有一些有位 &有趣的部分,但我不能把所有的部分放在一起.例如,presenceabsencevalidates_with(但最后一个感觉太重了).

I thought about using a validator, but I couldn't find one that handled associated objects in this way. There are some that have bits & pieces that are interesting, but I can't quite fit all the pieces together. For instance, presence is interesting as is absence and validates_with (but this last one feels too heavy).

建议?

推荐答案

很可能最好的方法是使用 after_add 回调(例如 here),这会将您现有的所有 设置为 false接受 记录通过 update_all 和接受设置为 true 的最新答案.这完全取决于你的逻辑.

Most likely the best way would be to use after_add callback (an example here), which would set to false all your existing accepted records via update_all and the latest answer with accepted set to true. It all depends on your logic.

您还可以使用一些其他回调,例如 before_save、before_update 等,具有类似的功能,具体取决于您的应用程序细节.

You can also employ some other callbacks such as before_save, before_update and such with the similar functionality depending on your application specifics.

它不会退出验证,但会有效地维护模型所需的状态.此外,验证的目的是在某些内容无效时向您发出警告,但我猜您想在没有此类失败的情况下保存您的对象,并只执行一个可接受的答案.

It is not quit a validation, but it will effectively maintain the required state of your model. Besides, the purpose of the validations to warn you when something is not valid, but I guess you want to save your object without such failures, and just enforce a single accepted answer.

如果您想在第一个答案被接受后停止添加答案,请告诉我.在这种情况下,它将需要不同的功能.

Let me know in case you want to stop adding answers after the first one was accepted. In this case it would require a different functionality.

这篇关于是否有可以用于所有关联记录上的特定属性的验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆