6

モデルにdocument列を追加したので、ファイルを追加できるようになりました。Posttxt

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 に答える