在我的Rails API / Angular应用程序中,我希望能够使用字段值搜索Rails表。目前,我在下面运行此代码,该代码允许按电子邮件ID搜索users表,并且它以JSON形式返回用户记录。
api / controllers / 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
get 'api/users/:id/query' => 'api/users#query'
示例网址
http://0.0.0.0:8080/api/users/1/[email protected]
范例传回JSON
{"id":14,"title":"Dr.","first_name":"John","last_name":"Smith","email":"[email protected]","job_title":"Head Bioligist","organisation":"NIH","phone_office":null,"city":null,"country":null,"approved":true,"admin":false,"template":false}
目前,这一切工作正常,但是有两个我无法解决的问题。
我希望url不包含:id,而我将id留在url中时找不到,Rails将查询参数视为id。我可以通过对伪造的id进行硬编码来使其工作,但这似乎对我来说不是正确的答案。
我想将任意参数散列传递给查询方法。它应基于哈希内容映射列。
如果params = {email:'[email protected]'},则它应该可以像现在一样工作,但是其他所需的选项可能是:
{job_title: 'Manager'}
{city: 'LA', last_name: 'Smith'}
我希望我会更改此代码,但不知道如何将任意元素传递到where。
queried_user = User.where(email: params[:email])
where方法可以接受哈希,因此您可以传递包含查询条件的参数哈希。请注意,将哈希传递给where方法时,只能使用相等和范围条件。只要确保就您的应用程序的安全性而言,您就受到了保护。例子:
queried_user = User.where(params[:user])
要摆脱路由文件中的:id,请定义类似于以下内容的新路由:
match 'api/users/query', to: 'users#query', as 'user_search'
然后使用“ user_search_path”将搜索发送到用户控制器的查询操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句