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 .
ActiveModelSerializers::Deserialization.jsonapi_parse(relationship_params['project'] evaluates to {} . Calling project return the equivalent of Project.first
def project
Project.find_by(ActiveModelSerializers::Deserialization.jsonapi_parse(relationship_params['project'], only: [:id]))
end
def relationship_params
return false unless params.dig(:data, :relationships)
params.require(:data).require(:relationships).transform_keys(&:dasherize)
end
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