LoginSignup
2
1

More than 5 years have passed since last update.

ActionControllerを継承したController外(Model, rake task等)でURLヘルパーを使用したい場合の対処法

Last updated at Posted at 2016-02-03

Context

  • hogefuga_url/higefoge_path などのurlヘルパーはController内で定義されており、ActionControllerを継承したController内では適切にパスとして機能する。
  • link_toで渡す"hogefuga_url" / "higefoge_path"を読み込んで適切なURLを生成・紐付けしてくれるのがURLヘルパー(別名:pathヘルパー)である。

  • サンプルコード(adminからuserへのメッセージを作成し、引数にメッセージ内容とリンクを渡している)

  task test_task: :environment do
    User.where(start_date: Date.today).each do |user|
      user.send_admin_message("message", edit_user_url(token: user.token))
    end
  end

Problem

  • 例えば、モデル内やrake task内において、あるurlを読み込みたい場合や引数で渡したい場合がある。そのときにただ foga_url を渡すと、NoMethodErrorが出てしまう。

Solution

  • 原因は、Model内やrake task内では Rails.application.routes.url_helpers 内で定義されているURLヘルパーがincludeされていないこと。
  • よって該当するrake taskやmodel内において、
include Rails.application.routes.url_helpers

を追加してあげれば良い。

2
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
2
1