10
8

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 5 years have passed since last update.

【Rails】Modelで定義した定数にViewからアクセスする方法

Last updated at Posted at 2020-02-14

表題の通り、定数にアクセスできずに困った人のための記事です。

結論

Model名::定数名とすればOKです。

解説

下記のUserクラスがあるとします。

models/user.rb
class User < ActiveRecord::Base
  MAX_NUMBER = 10
  ...
end

Viewから参照するには、下記のようにします。

views/xxx.html.erb
最大値は#{User::MAX_NUMBER}です。

 
これが下記のようになっていると、

views/xxx.html.erb
最大値は#{MAX_NUMBER}です。

uninitialized constant ActionView::CompiledTemplates::MAX_NUMBER

そんな定数は無いと怒られてしまいます。

以上です!

10
8
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
10
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?