6

我在我的模型中添加了一个documentPost,所以现在我可以向其中添加txt文件:

post.rb:

has_attached_file :document
validates_attachment_content_type :document, :content_type => 'text/plain'

安慰:

 #<Post id: 92, content: "document upload test", user_id: 1, created_at: "2013-01-02 10:23:13", updated_at: "2013-01-02 10:23:13",
 title: "document upload test", document_file_name: "test.txt",
 document_content_type: "text/plain", document_file_size: 15,
 document_updated_at: "2013-01-02 10:23:13">

所以现在,我想把里面的内容test.txt变成原始文本。所以我可以在我的控制器中做这样的事情:

@post.content = [TEXT INSIDE test.txt]

有什么建议么?

4

1 回答 1

5

使用before_save 回调,然后找到路径,打开文件并调用File::read打开的文件。

class Post
  before_save :contents_of_file_into_body

  private
  def contents_of_file_into_body
    path = document.queued_for_write[:original].path
    content = File.open(path).read
  end
end
于 2013-01-02T10:46:11.277 回答