I want to assign a progressive number to an attribute.
I think that I can do this in the model
class Model < ActiveRecord::Base
before_validation(:on => :create) do
attribute = Model.count + 1
But there is no method count for Model.
Is Model just an example, or did you use that as your model name?
The real code is:
class FirePrevention < ActiveRecord::Base
default_scope :order => 'practice_number ASC'
before_validation(:on => :create) do
practice_number = self.count + 1
end
It says undefined method count...........
You may be getting a funny self there, then. Try this instead:
practice_number = FirePrevention.count + 1
It's the same, same error.
Have you tried this in rails console? In a new blank project, maybe?
That work if I call FirePrevention.count from a controller.
That actually makes a ton of sense, since the Model has no notion of the collection of sibling objects, only the Empyrean ideal of the Model that spawned them. But count is a property of a collection of unique objects.
Does everyone here realize that the 'id' is typically tied to a database column that is set to auto-increment (in whatever fashion the underlying database supports) for the primary key?
Also, if you ever delete a record, the .count will decrease and you'll get a duplicate for the next created record.
Perhaps you want FirePrevention.max(&:id)+1 if you can't just rely on the id directly.
Yes, it's apparently mixed into the controller, so you would have to do that there. I could see you adding this to the create method directly, or you could put it in a before_save there, it should work fine. Probably exactly the same code as your initial example.