我希望网址为www.mydomain.com/category/parent/child
,因此我的路由为get '/category/:name(/:name)' => 'categories#show'
我有一张桌子'类别'像
> desc categories;
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| public_id | int(11) | YES | | NULL | |
| name | varchar(255) | YES | | NULL | |
| root | int(11) | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
+------------+--------------+------+-----+---------+----------------+
我像这样填充数据库
Category.create(:public_id => 60, :name => "nues", :root => 0)
Category.create(:public_id => 61, :name => "artistiques", :root => 60)
Category.create(:public_id => 62, :name => "glamours", :root => 60)
Category.create(:public_id => 63, :name => "fetichiste", :root => 60)
Category.create(:public_id => 69, :name => "autres", :root => 60)
因此,如果root = 0
,那么它就是父类别。如果root > 0
该类别是根值
我的Categorie_Controller显示操作。问题是类别的名称相同,如“自然” - >其他'和'肖像 - >其他&#39 ;.所以我的find_by_name无法正常工作
def show
if request.get?
@photographs = Category.find_by_name(params[:name]).photographs
end
end
是否可以通过我的路线系统做我想要的事情?
答案 0 :(得分:1)
不要为param变量选择相同的名称。
# config/routes.rb
get '/category/:name(/:child_name)', to: 'categories#show'
# app/controllers/categories_controller.rb
def show
# Now params[:name] and params[:child_name] are available
# BTW: Only get requests will be routed anyways with your routes definition
@photographs = if params[:child_name].present?
parent = Category.find_by!(name: params[:name])
Category.find_by!(name: params[:child_name], root: parent.id)
else
Category.find_by!(name: params[:name])
end
end
希望这些提示有所帮助。
此外,您可以通过在控制器操作中提升它们来查看传入的参数:
raise params.inspect