How to return null if no result found with find_by?

4

I'm getting a return as array ( [] ) from a scope with find_by and I want the return to be empty ( null ).

Here are some snippets of the code:

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

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

It is a has_many relationship, so it is normal to return an array if no result was found.

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

As I'm using a scope, and I expect only one result of the filter, I thought it would return null if no result was found.

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

    
asked by anonymous 25.01.2017 / 12:03

2 answers

2

The way I found it to solve this was by using a .present? within a conditional in the place where I make the call of the 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 do this, an error of ActiveModel::Serializer will be displayed.

#<NoMethodError: undefined method 'read_attribute_for_serialization' for #<ActiveRecord::AssociationRelation []>>
    
25.01.2017 / 12:22
1

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

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

to return the first result or nil .

    
29.03.2017 / 00:00