Mathieu Mathieu - 1 month ago 15
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

With Ruby < 2.3:

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

or

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