Reputation: 1417
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
Upvotes: 2
Views: 489
Reputation: 23307
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 without tests:
def test_change_solo_true_to_false
Artist.create :solo => true
assert Artist.change_solo!
assert !Artist.solo?
end
def test_change_solo_false_to_true
Artist.create :solo => false
assert Artist.change_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.
Upvotes: 10
Reputation: 533
Just FYI, ActiveRecord::Base#update_attribute does not run validations, so you rarely want to use this method.
Upvotes: 0
Reputation: 11395
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.
Upvotes: 28
Reputation: 1817
Something like this :
Class Artist < ActiveRecord
attr_accessible :solo #boolean
def change_solo!
self.solo = !self.solo
self.save
end
end
?
Upvotes: 4