问题描述
我有一条路线获得‘/ catalog /:gender /’=> catalog#gender
。 :gender
参数在我的控制器中使用,因此 @products = Product.where(gender:params [:gender])。all
。
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
.
所以我可以使用 / catalog / male /
来获取所有男性产品和 / catalog / female /
获取所有女性产品。问题是,是否有人可以同时传递 male
和 female
参数并获取所有产品? / p>
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?
推荐答案
您可以通过 / catalog / all /
获得所有产品,并在您的控制器中:
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
或渲染 gender
参数可选 get'/ catalog(/:gender)'
并然后在您的控制器中:
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.
我们创建一条路径 / catalog /
,并提交一个 / catalog这样的数组吗?性别[] =男性和性别[] =女性
。
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?
这篇关于有没有办法在路由参数中放入多个参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!