Routes 路由

Rails路由种类 (一般路由,命名路由)

使用 :except排除某个路由
resource :posts, :except => :show

可以添加额外一般路由 :to (不同的请求方法有区分 get,post)
get 'posts/:id', :to => 'post#show'
post 'posts/:id', :to => 'post#show'

命名路由: 添加 :as => XXXXX
get 'posts/:id', :to => 'post#show' :as => 'post_show' #这样生成的路由会自动生成路由路径名称 ex. post_show_path

view界面内可以直接使用rails方法创建一个超链接
<%= link_to 'id为1的微博', {:controller => 'posts', :action => 'show', :id => 1} %> #这个方法为一般路由添加方法
<%= link_to 'id为1的微博',show_post_path(1) %> #这个方法为命名路由添加方法

Rails.application.routes.draw do

  resources :posts do
    # get 'recent', :on => :collection
    collection do  #集合路由
        get 'recent'
        get 'today'
    end
    # member do  #成员路由
    #   get 'recent'
    # end
  end


  root 'posts#index'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

资源路由 (rails中最常用的路由方式)

资源路由可渲染和不渲染视图

资源路由创建:

  • 在controller里面需要创建相应的方法
def recent
  #具体函数写法按需求
end
  • 创建视图文件 recent.html.erb (需要创建时, 视图文件根据具体需求构建)
视图文件
  • 在routes文件中添加路由 (扩展资源路由添加)
    • 集合路由添加方式 (两种写法)
      生成的路由信息 posts/recent

resources :posts do
get 'recent', :on => :collection
end

resources :posts do
collection do #集合路由 需要添加多个时 采用这种写法
get 'recent'
get 'today'
end
end

 - 成员路由添加 (生成的路由信息会附加路由的id  ex. posts/:id/recent )

resources :posts do
collection do #集合路由
get 'recent'
get 'today'
end
member do #成员路由
get 'recent'
end
end


总结:rails中资源路由是最常用的路由方式,可以使用集合路由或者成员路由为其添加路由方法




最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,837评论 18 139
  • 参考 RailsGuides中的Rails Routing from the Outside In 简介 Rail...
    零小白阅读 7,483评论 0 15
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,789评论 0 23
  • 心中有一句话,年轻的我们一无所有,但年轻的我们将拥有一切。
    六月风雪阅读 156评论 0 0
  • 《快乐星球4》第五集里面说到:名字是父母送给我们的第一份礼物。确实,大部分的家长从知道孩子的存在,甚至还没出...
    冰镇火药阅读 2,543评论 22 12