1

I need to insert the contents of a file into the database during a migration (Rails 3.2.13). What's the proper way to reference a file that is elsewhere in the project?

db/migrate/the_migration.rb

class ...
  content = File.read("../../app/views/layours/application.html.erb")
end

The relative path doesn't seem to work - I get:

No such file or directory - ../../app/views/layouts/application.html.erb

How can I map this path to an absolute path?

Josh M.
  • 26,437
  • 24
  • 119
  • 200

2 Answers2

2

You can try the code below:

class ...
  path = File.expand_path('../../app/views/layouts/application.html.erb', __FILE__)
  content = File.read(path)
end
diegog
  • 1,731
  • 9
  • 8
  • It worked, except for some reason I had to go up three directories instead of two. Not sure why that would be. – Josh M. Feb 14 '14 at 18:54
0

assuming you are using rake to apply an active record migration. The file path will be relative to where you started rake which I'm sure will be the projects root.

The file path would be:

content = File.read("app/views/layouts/application.html.erb")

  • This is not the case for me. I'm using rake at the root project path and I had to go up three levels to get to `/app`. If what you said is true, I should just have to use the path `/app/views/...`. If it matters, I'm using Aptana Studio/Eclipse and running rake from within the console in Eclipse. – Josh M. Feb 14 '14 at 18:57
  • I'm not sure about the eclipse console. you don't want to use '/app/viwes/' you would want 'app/views/' without the first slash. If you create a dummy migration and add puts Dir.pwd to the top when the migration runs you should find out which directory its running from. – Cryptographic_ICE Feb 14 '14 at 20:05
  • Yeah the first `/` was a typo which I noticed after SO's edit period has expired! :( Thanks. – Josh M. Feb 15 '14 at 01:36