views:

17

answers:

3

I have a model, called Book, that has the fields title and filename (and other fields but they are unrelated). I'd like that the filename field was automatically created using the title, thus in my Book.rb:

class Book < ActiveRecord::Base
  # ...

  def title=(title)
    self.filename = sanitize_filename(title)
    self.title = title
  end

  # ...
end

Because of self.title = title it's going in a infinite recursion. How could I avoid that?

Thanks!

+1  A: 

Try this way

class Book
  def title=(title)
    self.filename = sanitize_filename(title)
    self[:title] = title
  end
end
Jesse Wolgamott
Exactly what I've been looking for. I've seen the same idea in Python. Thank you very much! Wonder how could I've been programming without knowing this... Thanks, again!
Albus Dumbledore
+2  A: 

You can write that on before_save

def before_save
  self.filename = sanitize_filename(self.title)
end
krunal shah
Thanks! I thought of that, too, but I wanted a different solution.
Albus Dumbledore
+1  A: 

There's a section in the ActiveRecord api on 'overwriting default accessors'. The suggested solution there is:

def title=(t)
  self.filename = sanitize_filename(t)
  write_attribute(:title, t)
end
Shadwell
I was looking for exactly this part of the doc, but thought that someone might already know that so they could help me out. Thanks a lot!
Albus Dumbledore