LearningROR LearningROR - 8 months ago 44
Ruby Question

.where returns nil exception if user does not enter anything rails 4

I want to query some data from table based on user for submission.

Its working fine but if I post nothing in the the fields and post my form, it returns me nil exception.

Is there a way we can deal with nil exception, or do I need to change query?

question_options = question.question_options.where(id: self.option_id).first


The simplest solution is to use try. For example:

question_options = question.question_options.where(id: self.option_id).try(:first)

The documentation for try is here