数据属性为空时 ActiveRecord 返回第一条记录

ActiveRecord returning first record when data attribute empty

我的控制器中有一个方法可以找到作为 json 传入的模型的关系。当所有预期的属性都存在时,它工作正常。但是如果我排除一个 'project',我的项目方法会给我第一个记录而不是 nil 或 Project.none .

所以当

ActiveModelSerializers::Deserialization.jsonapi_parse(relationship_params['project'] 计算为 {} 。调用项目 return 相当于 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

您可以验证您的参数哈希。但是很正常,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