Rails Route 记录

namespace

namespace :admin do
  resources :articles
end
# GET | /admin/articles | admin/articles#index | admin_articles_path

scope

  1. ‘/name’
# 
scope 'admin' do
  resources :articles
end
# 或者
resources :articles, path: '/admin/articles'
# GET | /admin/articles | articles#index | articles_path
  1. module
scope module: 'admin' do
  resources :articles
end
# GET | /articles | admin/articles#index | articles_path
  1. shallow_path
scope shallow_path: 'admin' do
  resources :articles do
    resources :comments, shallow: true
  end
end
# GET | /articles/:id/comments | comments#index | article_comments_path(article)
# GET | /admin/comments/:id    | comments#show  | comment_path(comment)
  1. as
scope as: 'admin' do
  resources :articles
end
# GET | /articles | articles#index | admin_articles_path
  1. shallow_prefix
# 为辅助方法添加指定前缀, 要配合 shallow 一起用
scope shallow_prefix: 'prefix' do
  resources :articles do
    resources :comments, shallow: true
  end
end
# GET | /articles/:id/comments | comments#index | article_comments_path
# GET | /comments/:id | comments#show | prefix_comment_path(comment)

resources

  1. shallow
# 浅层嵌套
resources :articles do
  resources :comments, only: [:index, :new, :create]
end
resources :comments, only: [:show, :edit, :update, :destroy]
# 也可以写成
resources :articles do
  resources :comments, shallow: true
  # shallow 只影响到自己和自己模块内的m, 也可用 shallow(&block) 嵌套 不可像shallow_prefix那样指定字符串
  resources :others
end
# GET | /articles/:id/comments | comments#index | article_comments_path
# GET | /comments/:id | comments#show | comment_path(comment)

ip 黑名单

class BlacklistConstraint
  def initialize
    @ips = Blacklist.retrieve_ips
  end
 
  def matches?(request)
    @ips.include?(request.remote_ip)
  end
end
 
Rails.application.routes.draw do
  get '*path', to: 'blacklist#index',
    constraints: BlacklistConstraint.new
end
# 或者
# *path 是通配符片段,可以在 params 中获取匹配到的路由 params[:path]
get '*path', to: redirect('/'), constraints: lambda {|request| request.remote_ip == '127.0.0.1'}

draw

可以使用 draw 引入外部路由,把路由模块化

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值