Reputation: 118
I have the following code:
class ArticlesController < ApplicationController
def new
p self.class.object_id
@article = Article.new
end
def create
p self.class.object_id
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
private
def article_params
params.require(:article).permit(:title, :text)
end
end
Rails creates a new instance of controller per request, so I supposed them to have different object ids. However, self.class.object_id
returns the same value within new
and create
actions. Why is that the case?
Upvotes: 0
Views: 99
Reputation: 15298
When you write self.class.object_id
, you are asking the object_id
of your class ArticlesController
, not instance. Of course, they will be the same.
Try self.object_id
or just object_id
, and you will see that they are different.
Upvotes: 4
Reputation: 9
Because the referent of self
is an object of ArticlesController
, when you started the server, ArticlesController
is assigned an object_id
. When you call it in context of the class, it returns the same object_id
each time.
Upvotes: 0
Reputation: 10043
In actions new and create, the object has not changed.
self.class
The same number will be returned on all calls to object_id for a given object, and no two active objects will share an id.[Object_id]
Upvotes: 0