简体   繁体   中英

ruby on rails iterating params

I have a client that is sending params such as age, gender, name and so on. I need to retrieve data from the table based on the params, but first I need to check for the presence of the param(to avoid a null param and therefore an empty result). The params are working as filters, so they can be triggered or they can be left blanck. What I am doing right now is

@retieve = Student.all
  unless params[:age].nil?
    @retrieve = @retrieve.where(age: params[:age])
end
   unless params[:gender].nil?
    @retrieve = @retrieve.where(gender: params[:gender])
end

and so on for every param I receive. This way I check if the filter has been selected, and if it has I use the selection as a parameter for the query It works, but as Ruby is known for the DRY statement, I am pretty sure someone out there knows a better way for putting this and to make this flexible. Thank you for whatever answer or suggestion you will provide!

This will work best if all of these filters were in a subhash of params that you can iterate over without including unwanted parameters (eg the :action and :controller parameters that rails adds)

Once you've done that you could do

(params[:filters] || {}).inject(Student.all) do |scope, (key, value)|
  scope.where(key => value)
end

There's a few ways to do this sort of thing and you have options for how far you want to go at this stage.

Two big things I'd consider -

1) Make nice scopes that allow you to send a param and ignore it if it's nil. That way you can just append another scope for each param from the form and it will be ignored without using if or unless

2) Move the search into a separate class (a concern) to keep your controller clean.

Here's a blog post that talks about some of the concepts (too much to post in this answer). There is lots of info on the web about this, I searched on the web under "rails search filter params concern" to get an example for you.

http://www.justinweiss.com/blog/2014/02/17/search-and-filter-rails-models-without-bloating-your-controller/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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