Mathieu Mathieu - 1 year ago 60
Ruby Question

Rails/Active Record- how to use 'take' if there is any matching record

I have a query that goes:

ModalType.where(id: modal['modal_id']).take.template

The problem is that i might run in cases where the query does not find any id: modal['modal_id'], then I get the error

undefined method `template' for nil:NilClass

How can I write something that would 'take' BUT only if where(id: modal_id) returns something (=is found) ?

Answer Source

With Ruby < 2.3:

object = ModalType.where(id: modal['modal_id']).take
if object
  # I don't know. it's up to you


ModalType.where(id: modal['modal_id']).take.try(&:template)

With Ruby >= 2.3 you can use safe navigation operator:

template = ModalType.where(id: modal['modal_id']).take&.template
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download