blow up when things are wrong

Post on 26-Jun-2015

85 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

When something unexpected happens, you should know about it immediately to make debugging and fixing the problem easier. Discusses ActiveRecord persistence APIs.

TRANSCRIPT

Blow up when things are wrong

ActiveRecord edition

Vesa Vänskä, Kisko LabsHelsinki Ruby Brigade, Rails Girls

When something is wrong, you should know

about it as fast as possible

#save vs #save!

foo.save!

# or

if foo.save # successelse # failend

The case of updating attributes

Validations Callbacks

#update_attributes ✔ ✔

#update_attribute ✖ ✔

Question

Which of #decrement, #decrement!, and

#decrement_counter skip validations/

callbacks?

Validations Callbacks

#decrement ✔ ✖

#decrement! ✖ ✔

#decrement_counter ✖ ✖

Making it simpler

14.6.2012 – #update_attribute is deprecated in 3.2 branch

14.6.2012 – #update_attribute was removed from 4.0 branch

24.7.2012 – #update_column was deprecated in 4.0 branch

26.7.2012 – Rails 3.2.7 release

30.7.2012 – #update_column is undeprecated in 4.0 branch

1.8.2012 – #update_attribute is undeprecated in 3.2 branch

25.8.2012 – #update_attribute is put back in 4.0 branch

9.8.2012 – Rails 3.2.8 release

• https://github.com/rails/rails/commit/b081f6b59fb3f15d12043072ad9b331ffd2bc56e

• https://github.com/rails/rails/pull/6738

• https://github.com/rails/rails/pull/1190

• https://github.com/rails/rails/commit/4ac81de52fbcdabc68f6d1fa8a5ee9ff7fff7df1

• https://github.com/rails/rails/commit/50bdb924ba26999a468ec4844917cefec39ba08c

• https://github.com/rails/rails/commit/81542f95d25825a7d3eff87d6f706661bf553b18

Links

I

What is thecurrent status?

After all this

•In Rails 4 the recommended way is to use #update with a hash

•#update_attributes is aliased to #update

•#update_attribute is still skipping validations

Vesa's laws ofupdating attributes

1.Use #update_attributes or use setters and #save/#save!

2.All other methods of updating attributes need an accompanying comment that explains why you didn't follow the first rule.

Useless ActiveResource information

•ActiveResource #update_attribute will run validations normally

Extra Ruby tip

{foo: "bar"}[:foo]

{foo: "bar"}.fetch(:foo)

{foo: "bar"}[:foo] #=> "bar"

{foo: "bar"}.fetch(:foo)#=> "bar"

{foo: "bar"}[:whatevs]

{foo: "bar"}.fetch(:whatevs)

{foo: "bar"}[:whatevs] #=> nil

{foo: "bar"}.fetch(:whatevs) #=> KeyError: key not found: :whatevs

{foo: "bar"}.fetch(:whatevs, :not_found)#=> :not_found

{foo: "bar"}.fetch(:whatevs) { 1 + 1 }#=> 2

top related