简体   繁体   English

使用URL_PARAMS查询Rails模型

[英]Query Rails models using URL_PARAMS

I am making Rails app and in my model I have Application model. 我正在制作Rails应用,在我的模型中有Application模型。 Application model belongs to User, and it has user_id as an attribute in Application model. 应用程序模型属于用户,并且在应用程序模型中具有user_id作为属性。 The route for getting all Applications is like below: 获取所有应用程序的途径如下:

GET    /applications(.:format)      Controller#Action applications#index                                                      

When I issue get request to above route, I get back all Applications. 当我发出对上述路线的获取请求时,我会取回所有应用程序。 Let's say there are two models: 假设有两种模型:

Application 1:
{
user_id:1,
data:{}
}

Application 2:
{
user_id:2,
data:{}
}

I would want to just query Application2 using user_id: 2. I issues GET request using url_params like following way but it did not work. 我只想使用user_id查询Application2:2.我像下面的方法一样使用url_params发出GET请求,但是没有用。

localhost:3000/applications?user_id=2

Is this not the right way of doing it? 这不是正确的方法吗?

It usually helps a lot to post more of your actual code. 通常,发布更多实际代码很有帮助。 If you post your models and existing index method code, I might be able to give you a more accurate response, but this should probably work based off my assumptions. 如果您发布模型和现有的索引方法代码,我也许可以为您提供更准确的答复,但这应该可以根据我的假设进行。

Find applications filtering based on the user_id using a where clause 使用where子句查找基于user_id的应用程序过滤

class ApplicationsController < ApplicationController
  def index
    @applications = Application.where(user_id: params[:user_id])
    # Render your json response using whatever method you want. Jbuilder, rabl, to_json, etc
  end
end

Hope that helps, feel free to add more info and I'll edit 希望对您有所帮助,请随时添加更多信息,我将进行编辑

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

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