LearningROR LearningROR - 1 year ago 79
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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download