Question:
What is the difference between these two possibilities?
//com @
@post = Post.find(params[:id])
//sem @
post = Post.find(params[:id])
Normally in controllers it is used with @
, but in each
functions of views it is usually used without @
, for example.
Are there any performance differences?
Answer:
variables that have @
are instance variables in the scope of the current object. variables without @
are local variables in the scope of the current object.
In the specific case of Rails, variables with @
used in controllers are made available to be used "inside" views.
For the each
that was mentioned, follow the example below:
@posts.each do |post|
<faz alguma coisa com 'post' aqui>
end
in this code snippet, the post
variable is local to the scope of the block in which it was defined, so it only exists within do |post| ... end
block. do |post| ... end
To better understand the differences between the types of variables, classes and objects, take a look at this link http://aprendaaprogramar.rubyonrails.com.br/index.rb?Chapter=09 .
About each
, look here http://aprendaaprogramar.rubyonrails.com.br/index.rb?Chapter=07