LoginSignup
2
1

More than 1 year has passed since last update.

url_forが見つからないと言われるエラー

Last updated at Posted at 2021-04-06

NoMethodError (undefined method `url_for'
というエラーが発生するので忘備録

class Gmap < ApplicationRecord
    require 'digest/md5'
    include Rails.application.routes.url_helpers
    validates :title, presence: true, length: { minimum: 1, maximum: 25 }
    validates :comment, presence: true, length: { minimum: 1, maximum: 255 }
    validates :latitude, presence: true
    validates :longitude, presence: true

    has_one_attached :image
    before_save :encrypt_magic_word

    def encrypt_magic_word
      if magic_word.present?
        self.magic_word = Digest::MD5.hexdigest(self.magic_word)
      end
    end
    def image_url
        # 紐づいている画像のURLを取得する
        image.attached? ? url_for(image) : nil
    end
    belongs_to :user

end

APIモードでアプリを作っているのですがRails6になってActive Storageを使うにあたって
url_forなんてメソッドは無いよというエラーが出たので調べると

include Rails.application.routes.url_helpers

をurl_forを使っている所にincludeしないと使えなかったので共有します。

ちなみに config/environments/development.rb
に下記も追加しないとダメです。

  Rails.application.routes.default_url_options[:host] = 'localhost'
  Rails.application.routes.default_url_options[:port] = 3000
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