问题
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