Wednesday 15 September 2010

Rails query by arbitrary column -



Rails query by arbitrary column -

in rails api / angular app, want able search rails tables using field values. have code below working, allows searching users table email id, , returns users record json.

api/controllers/users_controller.rb

def query # email queried_user = user.where(email: params[:email]).first if !queried_user.nil? render json: queried_user, root: false else render json: {error: 'does not exist'}, status: :not_found end end

config/routes.rb

get 'api/users/:id/query' => 'api/users#query'

example url

http://0.0.0.0:8080/api/users/1/query?email=testuser1@example.com

example returned json

{"id":14,"title":"dr.","first_name":"john","last_name":"smith","email":"testuser1@example.com","job_title":"head bioligist","organisation":"nih","phone_office":null,"city":null,"country":null,"approved":true,"admin":false,"template":false}

this working fine @ present, there 2 issues cannot resolve.

i url not contain :id find when leave id out of url, rails treats query parameter id. can made work hard-coding false id, doesn't seem right reply me.

i pass abitary param hash query method. should map columns based on hash contents.

if params = {email: 'testuser1@example.com'} should work now, other desired options might be:

{job_title: 'manager'} {city: 'la', last_name: 'smith'}

i expect alter code, don't know how pass arbitrary elements where.

queried_user = user.where(email: params[:email])

the method can take hash, hence can pass param hash containing status query. note equality , range conditions can used when passing hash method. sure in terms of security of application covered. example:

queried_user = user.where(params[:user])

to rid of :id in routes file define new route similar this:

match 'api/users/query', to: 'users#query', 'user_search'

and utilize 'user_search_path' sending search query action of users controller.

ruby-on-rails

No comments:

Post a Comment