You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails实现:当SurveyQuestion的answer_type为Radio Button时验证SurveyAnswer的answer_content必填

解决SurveyAnswer关联SurveyQuestion时的验证需求

没问题,我来帮你调整这个验证逻辑~

你现在的需求是:当关联的SurveyQuestion的answer_type为"Radio Button"时,SurveyAnswer的answer_content必须存在。原来的验证逻辑刚好是反过来的,而且需要注意answer_type是在关联的SurveyQuestion模型里,所以我们需要在SurveyAnswer中通过关联对象来判断这个条件。

修改后的SurveyAnswer模型代码如下:

class SurveyAnswer < ApplicationRecord
  belongs_to :survey_question

  # 当关联的survey_question的answer_type是Radio Button时,验证answer_content必须存在
  validates_presence_of :answer_content, if: -> { survey_question&.answer_type == "Radio Button" }
end

代码说明:

  • 使用lambda(-> { ... })作为if的条件,这样可以延迟执行判断逻辑,确保在验证时才去获取关联的survey_question对象。
  • &.是Ruby的安全导航操作符,用来避免当survey_question为nil时(比如还没关联到问题的答案)调用answer_type引发NoMethodError。
  • 如果你的Rails版本低于5,belongs_to默认不是必填的,建议加上validates_presence_of :survey_question来确保答案一定关联到对应的问题,这样验证逻辑会更可靠。

内容的提问来源于stack exchange,提问作者user9737634

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:42:12