OREMATOPEE

プログラミング、気になったこと、メモ書き...etc

モデルでURLヘルパーメソッドを使う

参考

Railsの不特定ModuleやClass(Modelなど)で`_path`を使う #Rails - Qiita

本題

config/routes.rb に以下のように書くことで URL ヘルパーメソッドを使えるようになる。

Rails.application.routes.draw do
  resources :reports
end

これで URL ヘルパーメソッドが定義されビューやコントローラーで使えるようになるが、モデルで使う場合は直接モジュールから呼び出すことで使用可能。

class Report
  def show_path_1
    reports_path
  end

  def show_path_2
    Rails.application.routes.url_helpers.reports_path
  end
end

report = Report.new
report.show_path_1
# => NameError: undefined local variable or method `reports_path' for Report:Class

report.show_path_2
# => "/reports"

ただ2017年のこちらこちらの記事ではモジュールを include したほうが速度的に早いらしいので、基本的には include したほうがよさそう。

class Report
  include Rails.application.routes.url_helpers

  def show_path_2
    reports_path
  end
end
report = Report.new
report.show_path_2
# => "/reports"
end