class Model < 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:
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.
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.
So the undefined method count rised by the model is correct?
How about a method to assign a progressive number to
FirePrevention.practice_number?
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.
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.
And even with the above you’ve got race conditions…
before_validation(:on => :create) do
default_scope :order => ‘practice_number ASC’
It’s the same, same error.
that
spawned them. But count is a property of a collection of unique
objects.
So the undefined method count rised by the model is correct?
How about a method to assign a progressive number to
FirePrevention.practice_number?
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.
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.