14

I am using Ruby on Rails and have a form that gets information from user input. I then want to take the user input and write it to a text file on the server side. I hope to save the file in somewhere such as /public/UserInput.txt.

Is there a way to use Ruby on Rails to do this? Or do I need a different language to do this such as PHP? In either case can anyone give me an example of how this is to be done?

Thanks in advance.

Update The code I am trying that is not giving me a text file is:

after_save :create_file 

def create_file 
parameter_file = File.new('C:\\parameter_file.txt', "w")   
parameter_file.puts(:parameter) 
end 
2
  • 1
    Does your server have permissions to write to that directory? What happens when another user wants to save a file and you overwrite it? Why aren't you using the block form of open, or, more simply File.write, so the file is automatically closed? Failing to close the file handle will consume all available file handles on your machine eventually and crash your code. Commented Nov 20, 2013 at 20:21
  • Thanks it was a permissions thing, but :parameters doesn't give me the user input from the form Commented Nov 20, 2013 at 20:35

1 Answer 1

26

This isn't really a rails specific problem. It can be tackled in plain ruby.

path = "/some/file/path.txt"
content = "data from the form"
File.open(path, "w+") do |f|
  f.write(content)
end

where target is where you want the file to go, and content is whatever data you're extracting from the form.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes I saw that, but how do I incorporate it into a site built with ruby on rails? would that code go in my views or model? I am confused on where to place it.
In your model, preferably. You don't want this kind of code in the view.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.