kikeda1104's blog

備忘録・技術に関することを書いています。(webエンジニア)

route.rb(namespace, member) (Rails 4.x)

Railsは、DSLが豊富ですので、覚えるのは大変ですね。 routesで使われるDSLの一部を紹介したいと思います。

routes.rb

URLから実行するControllerのactionとのひも付けを表すファイルです。

namespace

informationコントローラのroutingを書く際に、information/welcomeなど名前空間を利用したい場合に利用します。 コントローラ名を利用していますが、もちろんそんなことをせずに、URLを設計できます。

namespace :information do
  get 'welcome'
end

# => information_welcome GET    /information/welcome(.:format)           information#welcome

member

memberは、information/:idのように使われます。サンプルコードを書くと。

resources :information do
  member do
    get 'welcome'
  end
end

# => welcome_information GET    /information/:id/welcome(.:format)       information#welcome

上記のように書きますね。

Rails tutorial、Rails Guideは目を通しておいて、tutorialのアプリを作ってみることをお勧めします。

参考
Rails Routing from the Outside In — Ruby on Rails Guides

以上です。