user6589814 user6589814 - 1 year ago 50
Ruby Question

Ruby on Rail - Create a folder and .txt file when create new record

I am building a application where companies can add many domains under their account.

What I want to achieve is: When a domains is

, in my
folder I want to create a new folder with folder name =>
domain id
and add a
file with same naming convention.


Public // This is public folder in Rails
--- domains
---- 2 // This is domain ID
--- 2.txt

What I have now:

class Domain < ActiveRecord::Base
def create_folder
dir = Dir.mkdir("#{Rails.root}/public/domains/#{}")
file = File.dirname("#{Rails.root}/public/domains/#{}/#{}.txt")

This does create the folder but doesn't creates the

Answer Source

File.dirname does not create a file.

You want:

filename = Rails.root.join("/public/domains/#{id}/#{id}.txt"), 'wb') do |file|
  file << "My content"
  file << "More content"

Be sure to create the directory before

As for your use case:

Don't use a file. Don't store it public. Use Redis or similar if needed. But first just try if your DB can't cope with the load. Or did you try and hit a limit?

Be aware that everything in /public is public which means that one can access it through your webserver.

A non Rails example:

require 'fileutils'
id = 123
filename = "/tmp/public/domains/#{id}/#{id}.txt"
FileUtils.mkdir_p(File.dirname(filename)), 'wb') do |file|
  file << "My content"
  file << "More content"