We have summarized the variables and constants that are often used in Rails.
--Variables --Can be changed --Constant --Constant not possible
--Valid only within methods and blocks
user_name = 'jon'
<% hoge = 'huga' %>
<div><%= hoge %><div>
def create
article = Article.find( params[:id])
return render_404 if article.blank?
end
--Variables that can be used in the same controller
@
at the beginning--Pass the instance variable defined in Controller Action to View.
def show
@user = User.find(params[:id])
end
[users/show.html.erb]
<div>USER ID:<%= @user.id %><div>
def show
user = User.find(params[:id])
end
[users/show.html.erb]
<div>USER ID:<%= user.id %><div>
-> Cannot be referenced
undefined local variable or method 'user'
--All Controllers can be used --Can be changed and referenced from anywhere in the program
@
at the beginning--Define in class
--Constant name --Capital letters, snake case
--Define common constants in [config / initializers / constants.rb] --Can be referenced in all Controllers and Views [config/initializers/constants.rb]
MAX_SIZE = 10
--To define the constants used in each Model, define them in the class of the model file. [user.rb]
class User
OFFICIAL_ID = 100
end
When referencing with Controller or View, write ʻUser :: OFFICIAL_ID`
Recommended Posts