Reputation: 337
EDITED:
I trying to refactore this:
self.before_create do |obj|
obj.position = self.class.count
end
to this:
self.before_create :set_position
private
def set_position
obj.position = self.class.count
end
But, Its displaying Error:
undefined local variable or method `obj'
How fix this?
Upvotes: 0
Views: 88
Reputation: 6222
class Something < ActiveRecord::Base
before_create :set_position
protected
def set_position
self.position = self.class.count
end
end
Be aware that if you use class variables you might run into trouble if your server uses multiple processes (@@count
getting out of sync between them). A functional style queries count
from the db.
Note: A lot of this behavior (including properly implemented atomic changes to lists) can be found in the acts_as_list gem, that used to be part of Rails a while back. I suggest using that.
Upvotes: 1
Reputation: 21791
class YourClass < AR
before_create :set_position
private
def set_position
self.position = @@count
end
end
The set_position
method is instance method, so self
is assigned to the instance. The count
I believe should be a class variable.
Upvotes: 2