0

I have two model association as follows: Survey_question and survey_answer.

Survey_question Model

class SurveyAnswer < ApplicationRecord
belongs_to :survey_question

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

Survey_question Model

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

I just to validate presence of survey_answer's answer_content when survey_question's answer_type is "Radio Button" ? how can I achieve this ?? thanks in advance.

1 Answer 1

1

I'm not sure if you are looking for an if or unless based on using != in your example, but try the following:

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

Sign up to request clarification or add additional context in comments.

4 Comments

I have answer_type in survey_question model and want to validate presence answer_content from survey_answer only if I have answer_type value i.e. radio button
So... Yes, I think this answers your question? Can you confirm whether it solves your problem? If yes, and you are happy with the solution, mark the answer as correct.
no it doesn't. can you tell me what does answer stands for ?
By using the above validation your SurveyAnswer will only validate the presence of answer_content when the related SurveyQuestion answer type is Radio Button. If you want to only validate the presence of answer_content when the type is not 'Radio Button' then replace the if with unless.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.