LoginSignup
1
1

More than 5 years have passed since last update.

URLの指定で毎回同じネームスペースを書くのがだるいときに有用な resolve メソッドの使用例

Last updated at Posted at 2017-09-25
require "action_controller/railtie"
require "active_model"
ActionPack::VERSION::STRING     # => "5.1.4"

class User
  include ActiveModel::Model
  def id; 1; end
  def persisted?; true; end
end

Class.new(Rails::Application).routes.draw do
  namespace :admin do
    resources :users
  end
  resolve "User" do |user|
    [:admin, user]
  end
end

include Rails.application.routes.url_helpers
default_url_options.update(only_path: true)

user = User.new
polymorphic_path(user)          # => "/admin/users/1"

user は admin ネームスペースの下にしかないのに :admin ばっかり書きとーないわってときに上の例のようにひっかけておくと User クラスに反応して :admin を指定していないにもかかわらず /admin/users/1 になってくれたりします。

別の使い方としてフロント側のユーザーの「ホーム」を意味する場所が / なのか /users/1 なのか /home なのか /profile なのか /my_page なのか /mypage なのかぐだぐだでよくわからなくなってしまう場合でも routes.rb の一箇所で定義しておけば、あとは抽象的にビューで link_to("ホーム", current_user) と書くだけでよくなったりします。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1