On 1 April 2011 10:21, Frederick Cheung <frederick.cheung@gmail.com> wrote:
>> UPDATE my_table SET field1 = 'new value' WHERE id = <non-existant-id-value>
>>
>> You'll get a message "no records were updated" - that's a successful
>> execution as far as SQL is concerned.
>
> Although you might expect rails to check the numbers of rows modified
> (as it does when optimistic locking is enabled) - Select * from foo
> where id ='non existant' will also execute just fine but rails chooses
> to make Foo.find(id) raise an exception in those cases
I agree it probably breaks the principle of least surprise, so I've
just had a rummage in active_record\base.rb (Rails 2.3.11)
Obviously, .find returns rows, so it's easy to raise an error if the
size of the returned array is nil, but I was curious about the return
value of create_or_update - so, when I try the previous example [1]:
> p = Person.create(:name=>'Bill')
> p.destroy
> p.name # => "Bill"
> p.save # => true
It works fine as the update method returns a true value if
quoted_attributes is empty (as it uses that to build the set of fields
to update - no fields to update == no query to run), but if you modify
the object before saving (eg, > p.name = "William"), it errors with a
"TypeError: can't modify frozen hash" when trying to update the
updated_at value because it's frozen the @attributes_cache collection
when destroy was called...
So yes, it probably would make more sense to have .save return false
or raise on saving a destroyed record - but it should raise if you try
to alter a destroyed record, and it makes not much sense to save a
record you've destroyed and not altered... :-/
I don't know which way to plump... any thoughts?
[1] That example is terribly contrived, and it's making it hard for me
to make up my mind if this behaviour is "bad" or not. Anyone got a
real-world example of where this is causing a problem?
--
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.
No comments:
Post a Comment