ruby on rails - Treating the file store as a column in the table -
i have blog model of content stored in file , remaining things stored in table.
my solution below
i created virtual attribute getter/setter method.
def content file.read(file_path) end def content=(html) file.open(file_path, "w") |file| file.write(html) end end but here have problem, want store html content file if record valid, when below in controller
blog.new(:content => html,:title => "title".......) my setter called first before other attributes set. since other attributes validated presence true record fail save still file stored.
so want solution file created if record valid , stored.
i think might better use before_save , after_find callbacks here. add accessors class allow attributes stored in memory when creating/updating content. when save database, save content file. when loading records database, load content file , store using same accessor
class post attr_accessor :content before_save :save_to_disk after_find :load_from_disk def save_to_disk file.open(file_path, "w"){ |f| f.write(content) } end def load_from_disk file.open(file_path){ |f| self.content = f.read } end end
Comments
Post a Comment