首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >添加模型验证{Rails}

问添加模型验证{Rails}
EN

Stack Overflow用户
提问于 2018-05-14 19:12:03
回答 1查看 32关注 0票数 0

我有两个模型关联: Survey_question和survey_answer。

Survey_question模型

代码语言:javascript
复制
class SurveyAnswer < ApplicationRecord
belongs_to :survey_question

validates_presence_of :answer_content, if: "answer_type!=Radio Button"
end

Survey_question模型

代码语言:javascript
复制
class SurveyQuestion < ApplicationRecord
belongs_to :user
belongs_to :survey

has_many :survey_answers
accepts_nested_attributes_for :survey_answers, allow_destroy: true

has_many :survey_responses
accepts_nested_attributes_for :survey_responses

validates :question_content, presence: true
validates :answer_type, presence:  true
end

我只是想验证一下,当answer_content _ answer_type是"Radio“时,是否存在answer_type?我怎样才能做到这一点?提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-05-14 19:22:05

我不确定您是基于在示例中使用if还是unless来查找!=,但请尝试以下操作:

validates_presence_of :answer_content, if: ->(answer) { answer.survey_question.answer_type == 'Radio Button' }

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50337449

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档