开发者

How can I write this more "ruby-ish"?

I got the following snippet

Class Artist < ActiveRecord
   attr_accessible :solo #boolean

  def change_solo!
    if self.solo == false
    开发者_StackOverflow中文版 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


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.


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.


Something like this :

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

?


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜