开发者

Rails: Updating two fields of an ActiveRecord instance simultaniously

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!


You can write that on before_save

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


Try this way

class Book
  def title=(title)
    self.filename = sanitize_filename(title)
    self[:title] = title
  end
end


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
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜