Mathieu Mathieu - 2 months ago 17
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) ?


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