How to return null if no result is found with find_by?

Asked

Viewed 82 times

4

I’m getting a return as an array ([]) of a scope with find_by and I wish the return to be empty (null).

See below some snippets of the code:

class Dispute::Conference < ApplicationRecord
  ...
  belongs_to :dispute, counter_cache: true

  scope :scheduled, -> { find_by state: :scheduled }
  ...
end

It’s a relationship has_many, then it is normal to return an array if no result is found.

class Dispute < ApplicationRecord
  ...
  has_many :conferences, dependent: :destroy
  ...
end

Since I’m using a scope, and I expect only one filter result, I thought it would return null if no results were found.

Is there any way to return null, for this specific case?

  • An important detail, I switched find_by for where, for some reason that I can not explain in some cases the return generates problems with the ActiveModel::Serializer.

2 answers

2


The way I found to solve this was by using a .present? inside a parole at the place where I make the call from scope scheduled:

class DisputeSerializer < ActiveModel::Serializer
  ...
  has_one :scheduled

  def scheduled
    Dispute::ScheduledSerializer.new object.conferences.scheduled if
      object.conferences.scheduled.present?
  end
end

One detail is that if you do not make this treatment an error of ActiveModel::Serializer will be presented.

#<NoMethodError: undefined method `read_attribute_for_serialization' for #<ActiveRecord::AssociationRelation []>>

1

The find_by always returns 1 or nil. How you switched to where, returns a collection or empty []. You can use

def self.scheduled where(state: :scheduled).first end

to return the first result or nil.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.