Antarr Byrd
Antarr Byrd

Reputation: 26151

ActiveRecord returning first record when data attribute empty

I have a method in my controller that finds relationships for a model being passed in as json. It works fine when all the expected attributes are present. But if I exclude one, 'project', my project method giving me the first record instead of nil or Project.none .

So when

ActiveModelSerializers::Deserialization.jsonapi_parse(relationship_params['project'] evaluates to {} . Calling project return the equivalent of Project.first

project method

def project
  Project.find_by(ActiveModelSerializers::Deserialization.jsonapi_parse(relationship_params['project'], only: [:id]))
end

relationship param

def relationship_params
  return false unless params.dig(:data, :relationships)
      params.require(:data).require(:relationships).transform_keys(&:dasherize)
end

Upvotes: 0

Views: 153

Answers (1)

Elena  Unanyan
Elena Unanyan

Reputation: 1209

You can verify your params hash. But it is normal, that Model.find_by({}) or Model.find_by(nil) returns fist record;

   def project
      find_params =ActiveModelSerializers::Deserialization.jsonapi_parse(relationship_params['project'], only: [:id])
      if find_params.present?
        Project.find_by(find_params)
      else
        nil
      end
    end

Upvotes: 2

Related Questions