Rails路由学习

一般路由

get  'meetings/:id', :to => 'events#show'
post 'meetings', :to =>'events#create'

events_controller的show和create action
简写

get 'meetings/:id' => 'events#show'

其中:id会被转车一个参数params[:id]传到Controller里。

match路由

match  ':controller(/:action(/:id(.:format)))', :via => :all

括号内的内容表示可有可无的内容

match '/:controller', via: :all
match '/:controller/:action', via: :all
match '/:controller/:action/:id', via: :all
match '/:controller.:format', via: :all
match '/:controller/:action.:format', via: :all
match '/:controller/:action/:id.:format', via: :all
match '/test_match/:action'=> 'test_match#:action' ,:via => :all

.format让路由可以接受.json、.xml参数,并且转成params[:format]参数中。

命名路由

get '/meetings' => 'events#index', :as => 'meetings'

其中的:as部分会产生meetings_path和meeting_url的Helpers,_path是相对路径,_url是绝对路径。

路由重定向

get '/foo' => redirect('/bar')
get "/ihower" => redirect("http://ihower.tw")

设置首页

root :to => 'welcome#show'

限定动词

match 'account/overview' => 'account#overview', :via=> :get
match 'account/setup' => 'account#setup', :via => [:get, :post]
match 'account/overview' => 'account#overview', :via => :all

scope规则

scope :controller => 'events', :path => '/foo', :as=>'bar' do
  get 'meetings/:id' => :show, :as =>'meeting'
  post 'meetings' => :create, :as=>'meerings'
end

产生bar_meeting_url和bar_meetings_url。

Namespace

namespace :admin do
  resources :projects
end

controller对应Admin::ProjectsController,网址为/admin/projects,而URL Helper如admin_projects_path。
每个Namespace都可以设置首页

namespace :admin do
  root 'projects#index'
end

这样连接/admin的时候就默认使用ProjectsController的index方法。

限定条件

限制:id是整数

match '/events/show/:id' => 'events#show', :constraints => {:id => /\d/}

甚至可以限定IP位置

constraints(:ip => /(^127.0.0.1$)|(^192.168.[0-9]{1,3}.[0-9]{1,3}$)/) do
    match "/events/show/:id" => "events#show"
end

自定义集合路由

resources :products do
  collection do
    get :sold
    post :on_offer
  end
end

产生sold_products_path和on_offer_products_path这两个URL Helper,产生出如products/sold和products/on_off

限定路由

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

推荐阅读更多精彩内容

  • 参考 RailsGuides中的Rails Routing from the Outside In 简介 Rail...
    零小白阅读 7,483评论 0 15
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,886评论 18 139
  • Rails路由学习 <%= link_to 'hello', {:controller => 'welcome',...
    yaya_pangdun阅读 310评论 0 0
  • 路由作用 1.根据实现定义的路由规则,检验URL请求,确定执行或者拒绝; 2.路由规则可自定义,隐藏了原URL地址...
    PlusNie阅读 2,700评论 1 5
  • cron不会加载用户原有的环境变量需要自己export环境变量,例如: 3,18,33,48, * * * * e...
    ibadplum阅读 1,275评论 0 0