0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】UrlHelperを拡張する

Posted at

独自のUrlHelperを定義したい

Rails.application.routes.url_helpers を include したClassを作成するとよいです。


class MyUrlResolver
  class << self
    include Rails.application.routes.url_helpers
  end

  # 独自定義したhelper
  def self.custom_users_path(user)
    if user.admin?
      admin_users_path
    else
      users_path
    end
  end
end

これで、

> MyUrlResolver.admin_users
=> "/admin_users"
> MyUrlResolver.users_path
=> "/users"

標準のUrlHelperに加えて、

> MyUrlResolver.custom_users_path(admin_user)
=> "/admin_users"
> MyUrlResolver.custom_users_path(normal_user)
=> "/users"

独自定義したUrlHelperも使うことができます。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?