【问题标题】:Treating the file store as a column in the table将文件存储视为表中的列
【发布时间】:2015-07-07 13:39:49
【问题描述】:

我有一个博客模型,其内容将存储在文件中,其余内容将存储在表中。

我的解决方案如下

我用 getter/setter 方法创建了一个虚拟属性。

def content
    File.read(file_path)
end

def content=(html)
    File.open(file_path, "w") do |file|
        file.write(html)
    end
end

但是这里我有一个问题,我只想在记录有效的情况下将 html 内容存储到文件中,但是当我在控制器中说如下内容时

Blog.new(:content => html,:title => "Title".......)

在设置其他属性之前首先调用我的 setter。 由于其他属性已通过存在验证,因此真实记录将无法保存,但我的文件仍将被存储。

所以现在我想要一个解决方案,仅当记录有效并存储时才会创建文件。

【问题讨论】:

    标签: ruby-on-rails virtual-attribute


    【解决方案1】:

    我认为在这里使用before_saveafter_find 回调可能会更好。向类添加访问器以允许在创建/更新内容时将属性存储在内存中。然后当您保存到数据库时,将内容保存到文件中。从数据库中加载记录时,从文件中加载内容并使用相同的访问器存储它

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-23
      • 2017-10-26
      相关资源
      最近更新 更多