rails 中的嵌套路由
Nested routes in rails
我是一个比 rails 更喜欢 sinatra 的人,并且从来没有做过需要 rails 的足够大的项目(我读过的所有资料都说 rails 更适合大型项目),现在我不得不做一个大型项目。我对 rails 的 url 结构感到非常困惑。我想要做的是 rails 等同于此:
get "/" do
erb :index
end
get "/home" do
erb :dashboard
end
get "/home/profile" do
erb :profile
end
get "/home/friends" do
erb :friends
end
在第一个我明白我应该输入 app/routes.rb
我应该输入 root home#index
并且在 home
控制器我应该输入 def index end
.
在第二个中,我明白我应该做同样的事情,除了用 home 替换索引。
但是对于第三个和第四个我不知道该怎么做。
此外,RESTful前两个的方法是什么?
你可以拥有这个:
resources :home do
collection do
get :profile
end
collection do
get :friends
end
end
end
这将为您提供如下路线:
profile_home_index GET /home/profile(.:format) home#profile
friends_home_index GET /home/friends(.:format) home#friends
声明根路径的标准方式:
root 'home#index'
对于第二个,你必须做:
get 'home' => 'home#dashboard'
这将为您提供这条路线:
GET /home(.:format) home#dashboard
一条路线可以用多种有效的方式定义。但是,Rails 在 Rails 应用程序中定义路由时应遵循一些约定。
我强烈建议您看一下 Rails Routing Guide
你可能想要这样的东西
root 'home#index'
get 'home' => 'home#dashboard'
get 'home/profile' => 'home#profile'
get 'home/friends' => 'home#friends'
记得使用命令 rake routes
来查看你所有的路线,它们通往哪里以及它们的名字是什么(如果有的话)
我一直不明白 RESTful 是什么意思,所以其他人必须回答你的那部分问题。
K M Rakibul Islam 向您展示了所谓的 "resourceful" 路由方式(因为它使用关键字 resources
),但看起来您只是在做静态页面这个阶段,所以没有必要。
做路线最简单的方法是使用这个公式:
method url => controller::action, as: route_name
其中 method
可以是 get
、post
、patch
或 delete
,因此您可以将不同的操作链接到相同的 URL 取决于请求使用的方法。
在路线上命名是可选的,但它为您提供了一种在视图中使用路线的简洁方式 (route_name_path
)
当您开始制作模型时,您会发现使用 resources
关键字会派上用场。了解它。
我是一个比 rails 更喜欢 sinatra 的人,并且从来没有做过需要 rails 的足够大的项目(我读过的所有资料都说 rails 更适合大型项目),现在我不得不做一个大型项目。我对 rails 的 url 结构感到非常困惑。我想要做的是 rails 等同于此:
get "/" do
erb :index
end
get "/home" do
erb :dashboard
end
get "/home/profile" do
erb :profile
end
get "/home/friends" do
erb :friends
end
在第一个我明白我应该输入 app/routes.rb
我应该输入 root home#index
并且在 home
控制器我应该输入 def index end
.
在第二个中,我明白我应该做同样的事情,除了用 home 替换索引。
但是对于第三个和第四个我不知道该怎么做。
此外,RESTful前两个的方法是什么?
你可以拥有这个:
resources :home do
collection do
get :profile
end
collection do
get :friends
end
end
end
这将为您提供如下路线:
profile_home_index GET /home/profile(.:format) home#profile
friends_home_index GET /home/friends(.:format) home#friends
声明根路径的标准方式:
root 'home#index'
对于第二个,你必须做:
get 'home' => 'home#dashboard'
这将为您提供这条路线:
GET /home(.:format) home#dashboard
一条路线可以用多种有效的方式定义。但是,Rails 在 Rails 应用程序中定义路由时应遵循一些约定。
我强烈建议您看一下 Rails Routing Guide
你可能想要这样的东西
root 'home#index'
get 'home' => 'home#dashboard'
get 'home/profile' => 'home#profile'
get 'home/friends' => 'home#friends'
记得使用命令 rake routes
来查看你所有的路线,它们通往哪里以及它们的名字是什么(如果有的话)
我一直不明白 RESTful 是什么意思,所以其他人必须回答你的那部分问题。
K M Rakibul Islam 向您展示了所谓的 "resourceful" 路由方式(因为它使用关键字 resources
),但看起来您只是在做静态页面这个阶段,所以没有必要。
做路线最简单的方法是使用这个公式:
method url => controller::action, as: route_name
其中 method
可以是 get
、post
、patch
或 delete
,因此您可以将不同的操作链接到相同的 URL 取决于请求使用的方法。
在路线上命名是可选的,但它为您提供了一种在视图中使用路线的简洁方式 (route_name_path
)
当您开始制作模型时,您会发现使用 resources
关键字会派上用场。了解它。