I cant seem to get find_by to work, when you query the results like
GET /users.json?first_name=Tyrone&last_name=Slothrop"
should return Users whose first_name is Tyrone and whose last_name is Slothrop.
It returns null because all the params are null in that query except first_name and last_name. Im stuck as to get it to accept the only the query params and search by those. any advice?
class Api::V1::UsersController < ApplicationController
def index
@users = User.find_by(id: params[:id], first_name: params[:first_name],
last_name: params[:last_name], email: params[:email],
city: params[:city], state: params[:state])
respond_to do |format|
format.json { render json: @users.to_json, status: :ok }
end
end
end
here is a link to mt full repo https://github.com/jslack2537/apiDemoApp
dev log output for request
Started GET "/api/v1/users.json?first_name=Tyrone&last_name=Slothrop" for 10.0.2.2 at 2020-04-01 02:42:17 +0000
Cannot render console from 10.0.2.2! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by Api::V1::UsersController#index as JSON
Parameters: {"first_name"=>"Tyrone", "last_name"=>"Slothrop"}
[1m[36mUser Load (4.4ms)[0m [1m[34mSELECT "users".* FROM "users" WHERE "users"."id" IS NULL AND "users"."first_name" = ? AND "users"."last_name" = ? AND "users"."email" IS NULL AND "users"."city" IS NULL AND "users"."state" IS NULL LIMIT ?[0m [["first_name", "Tyrone"], ["last_name", "Slothrop"], ["LIMIT", 1]]
↳ app/controllers/api/v1/users_controller.rb:5
Completed 200 OK in 7ms (Views: 0.1ms | ActiveRecord: 4.4ms)
EDIT*** I now receive this error with my updated code NoMethodError (undefined method `split' for nil:NilClass):
class Api::V1::UsersController < ApplicationController
def index
ids = params[:id].split(",")
if params[:id].present?
@users = User.where(user_params.merge!(id: ids)).paginate(:per_page => params[:size], :page => params[:page]).order('id DESC')
respond_to do |format|
format.json { render json: @users.to_json, status: :ok }
end
else
@users = User.where(user_params).paginate(:per_page => params[:size], :page => params[:page]).order('id DESC')
respond_to do |format|
format.json { render json: @users.to_json, status: :ok }
end
end
end
private
def user_params
params.permit(:first_name, :last_name, :email, :city, :state)
end
end