简体   繁体   English

Rails按任意列查询

[英]Rails query by arbitrary column

In my Rails API / Angular app, I want to be able to search Rails tables using field values. 在我的Rails API / Angular应用程序中,我希望能够使用字段值搜索Rails表。 I currently have this code below working, which allows searching the users table by email id, and it returns the users record as JSON. 目前,我在下面运行此代码,该代码允许按电子邮件ID搜索users表,并将用户记录返回为JSON。

api/controllers/users_controller.rb API /控制器/ users_controller.rb

def query  # by 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 配置/ 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 示例返回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 is all working fine at present, but there are two issues I cannot resolve. 目前,这一切都很好,但是有两个我无法解决的问题。

  1. I would like the url to not contain an :id I find when I leave the id out of the url, Rails treats the query parameter as the id. 我希望URL中不包含ID时才找到该URL:Rails将查询参数视为ID。 I can made it work by hard-coding a fake id, but it doesn't seem like the right answer to me. 我可以通过对伪造的id进行硬编码来使其工作,但这似乎对我来说不是正确的答案。

  2. I would like to pass an abitary param hash to the query method. 我想将任意参数哈希传递给查询方法。 It should map the columns based on the hash contents. 它应基于哈希内容映射列。

if params = {email: 'testuser1@example.com'} then it should work as now, but other desired options might be: 如果params = {email:'testuser1@example.com'},则它应该可以像现在一样工作,但是其他所需的选项可能是:

{job_title: 'Manager'}
{city: 'LA', last_name: 'Smith'}

I expect I will change this code, but don't know how to pass arbitrary elements to the where. 我希望我会更改此代码,但不知道如何将任意元素传递到where。

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

The where method can accept a hash, therefore you can pass the param hash containing the condition for the query. where方法可以接受哈希,因此您可以传递包含查询条件的参数哈希。 Just note only equality and range conditions can be used when passing a hash to the where method. 请注意,将哈希传递给where方法时,只能使用相等和范围条件。 Just be sure that in terms of security of your application you are covered. 只要确保您的应用程序的安全性得到了保障。 example: 例:

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

To get rid of the :id in your routes file define a new route similar to this: 要摆脱路由文件中的:id,请定义类似于以下内容的新路由:

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

and then use the 'user_search_path' for sending the search to the query action of the users controller. 然后使用“ user_search_path”将搜索发送到用户控制器的查询操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM