简体   繁体   中英

Query Strings in Ruby on Rails

I am in an App Development class and we have an assignment where I need to allow a certain rails url to be filterable.

Basically, the route /dishes should yield all the "dishes" in our database and the route /dishes?cuisine_id=# should filter the dishes such that only those with cuisine_id = # show up.

My code is as follows:

if params[:cuisine_id].blank?
    a = Cuisine.all
    b = Cuisine.where({:id=>a})
    c = Dish.where({:cuisine_id=>b})
    render({:plain=>c.to_json})
  else 
    a = params.fetch("cuisine_id")
    b = Cuisine.where({:id=>a})
    c = Dish.where({:cuisine_id=>b})
    render({:plain=>c.to_json})
  end
end

I've narrowed down the issues to the first line with the if statement

if params[:cuisine_id].blank?

and the assignment to a in the else.

(`a = params.fetch("cuisine_id")`)

In the first, I am having an issue telling Ruby/Rails to search for a query string. I would like that if statement to say if (query string does not exist) but I'm not sure syntactically how to do that, and after a lot of googling, it looks like .blank? is the best option but I'm not sure how to use it. In the second problematic line, I'm having an issue pulling information from the query string. I know I want the variable a to be equal to the value in the query string, but similarly to above, I'm not sure syntactically how to do that.

If you have any clarifying questions, I'm happy to answer them!

Thank you so much, and I appreciate any and all help.

def index
  @dishes = Dish.all
  @dishes = @dishes.where(cuisine_id: params[:cuisine_id]) if params[:cuisine_id].present?
  @dishes = @dishes.where(foo: params[:foo]) if params[:foo].present?
  # ...
end

.present? is the inverse of .blank? .

If you wanted to really dynamically add scopes from the params could just filter out the keys you want from the params and pass it to where:

filters = params.permit(:cuisine_id, :foo, :bar) # create a new hash with only these keys
                .select{ |k,v| v.present? } # filter out empty params
@dishes = Dish.all.where(filters)

You also might want to read up about nested routes as another way to do this would be to declare the route as /cuisines/:cuisine_id/dishes .

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