Ruby on Rails
Thursday, March 31, 2011
On Thu, Mar 31, 2011 at 9:06 AM, Alexey Muranov <lists@ruby-forum.com> wrote:
I am posting a related question in the same thread.
It is more of a philosophical question.
Can anybody please give me some philosophical explanation why the
following behavior of ActiveRecord is considered ok (or should i submit
a bug report/feature request?):
In console:
> p = Person.create(:name=>'Bill')
> p.destroy
> p.name # => "Bill"
> p.save # => true
Nothing is saved in the database, but what disturbs me more is that
"save" returned true in such case.
In this first example you are inializing an object instance of Person by calling the "create" method. The "create" method of class Person does a "create" to the database where as the method "new" does not. The "destroy" method you called sends a destroy to the database for the record based on that id but does not destroy the obect instance. This is because object is not a pointer to the database record, it's an instance of the class Person. This is why you can still retrieve the name from your object instance later by calling the method "name". The "save" method should be doing the action of create or update in the database (depending on if the "new" or "create" methods were called to inialize the object instance). It returning "true" is strange since the record in the database is neither being created or updated. That may indeed be a bug.
A more elaborate version:
> p = Person.create(:name=>'Bill')
> p.id # => 1
> pp = Person.find(1)
> pp.destroyed
> p.persisted? => true
> p.destroyed? => false
> p.save # => true
but the database is empty.
Again, what bothers me the most is the "true" returned by "save".
In this example you are inializing two seperate object instances of the class Person. One by calling the method "create" and the second by finding the first record in the database. Again, object instances are not pointers to the database record. The objects "p" and "pp" are totally seperate. Like above, activating the "destroy" method sends a destroy to the database based on the id in the object but does not destroy the calling object or any other object that happens to have the same id value. The "save" method returning true is strange since the record with the id value of 1 can't be created again or updated.
Someone else might know more as to why "save" returns true in this case. If not, then it is most likely a bug.
B.
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment