# File creation in Rails

**URL:** <https://www.ruby-forum.com/t/file-creation-in-rails/192479>\
**Category:** Rails\
**Created:** [July 30, 2010, 11:16pm UTC](https://www.ruby-forum.com/t/file-creation-in-rails/192479 "2010-07-30T23:16:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![silver-spoon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/aeb1de/32.png) [@silver-spoon](https://www.ruby-forum.com/u/silver-spoon)\
**Post date:** [July 30, 2010, 11:16pm UTC](https://www.ruby-forum.com/t/file-creation-in-rails/192479/1 "2010-07-30T23:16:02Z")

</div>

I am passing the contents of a textarea in my rails view to the server  
by a POST call. How can I store the contents as a separate file, say  
contents\_userId.txt on my server and at the same time store my file in  
database allowing me to access the various files a single user  
has…or for any other purpose.

---

<div class="post-metadata">

**Author:** ![silver-spoon](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/aeb1de/32.png) [@silver-spoon](https://www.ruby-forum.com/u/silver-spoon)\
**Post date:** [August 3, 2010, 12:32pm UTC](https://www.ruby-forum.com/t/file-creation-in-rails/192479/2 "2010-08-03T12:32:58Z")

</div>

To access files in rails, you can use the Ruby File Class

[http://ruby-doc.org/core/classes/File.html#M002579](http://ruby-doc.org/core/classes/File.html#M002579)

You can put this into a method in the model. Then either call it  
specifically from the controller, or use an after\_update callback to  
automatically create the file after the object has been saved to the  
database

def save\_file(filename)  
File.open “#{RAILS\_ROOT}/tmp/#{filename}”, ‘w’ do |f|  
f.write contents  
end  
end

Tonypm
