Is there a way to put multiple parameters in routing parameters?

扶醉桌前 提交于 2019-12-08 11:48:32

问题


I have a route get '/catalog/:gender/' => 'catalog#gender'. The :gender param is used in my controller like so @products = Product.where(gender: params[:gender]).all.

So I can use /catalog/male/ to get all male products and /catalog/female/ to get all female products. The question is, is there a way somebody could possibly pass both male and female parameters and get all the products?


回答1:


You can pass /catalog/all/ to get all products, and in your controller:

if params[:gender] == "all"
  @products = Product.all
else
  @products = Product.where(gender: params[:gender])
end

Or render gender params optional get '/catalog(/:gender)' and then in your controller:

if params[:gender]
  @products = Product.where(gender: params[:gender])
else
  @products = Product.all
end

To complete answer, Query string can resolve your issue too.

Let's create a route /catalog/, and submit an array like /catalog?gender[]=male&gender[]=female.

# params[:gender] = ["male", "female"]
# SELECT "catalogs".* FROM "catalogs" WHERE "catalogs"."gender" IN ('male', 'female')
@products = Catalog.where(gender: params[:gender])

Answers to complete this solution:

  • Correct way to pass multiple values for same parameter name in GET request
  • How to pass an array within a query string?


来源:https://stackoverflow.com/questions/37771904/is-there-a-way-to-put-multiple-parameters-in-routing-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!