views:

210

answers:

4

Hi folks

I got the following snippet

Class Artist < ActiveRecord
   attr_accessible :solo #boolean

  def change_solo!
    if self.solo == false
     self.solo = true
    else
     self.solo = false
    end
   self.save
  end

end

Is there a better way to write that? Thanks in advance cheers tabaluga

+3  A: 

Something like this :

Class Artist < ActiveRecord 
attr_accessible :solo #boolean 
  def change_solo! 
   self.solo = !self.solo
   self.save 
  end 
end 

?

OMG_peanuts
thanks alot! I'll try that
tabaluga
+24  A: 

Don't write this method. Use ActiveRecord::Base#toggle! instead:

artist_object.toggle!(:solo)

This method also exists in Rails 2, if you haven't upgraded yet.

wuputah
Thanks, didn't know about that method yet.
captaintokyo
Wow! thankyou for sharing this gem
tabaluga
@tabaluga, you can change your accepted answer. Just sayin'...
Mark Thomas
@Mark Thomas: no worries.
wuputah
+10  A: 

Aha! I can shrink it even further, heh:

def change_solo!
  update_attribute :solo, !solo
end

This does the save automatically.

But it wouldn't be complete with out tests:

def test_change_solo_true_to_false
  Artist.create :solo => true
  Artist.solo!

  assert !Artist.solo?
end

def test_change_solo_false_to_true
  Artist.create :solo => false
  Artist.solo!

  assert Artist.solo?
end

By the way, above I use the convention that any boolean attribute in ActiveRecord can have a question mark at the end to make it more self-explanatory.

Jaime Bellmyer
Perfect! Thumbsup and a big Thankyou
tabaluga
You should also assert that the record was saved (that the method returned true).
wuputah
A: 

Just FYI, ActiveRecord::Base#update_attribute does not run validations, so you rarely want to use this method.

ajsharp