Follow these steps if you wish to add a sitemap.xml generator to a rails application. The idea is to generate a sitemap.xml for selected records from the database, in this case they are Articles and Categories. This sitemap is pinged to popular search engines like google, yahoo, bing and ask.
Step 1:
Add a sitemap.rb file to your lib folder. Get it from git://gist.github.com/288069.git
Make sure you replace Article and Category model by the desired models.
Step 2:
Add the following rake task:
namespace :sitemap do
task :generate => :environment do
sitemap = Sitemap.create!('http://www.domain.com')
end
end
Step 3:
Schedule ‘rake sitemap:generate’ using a cron or add it to your deploy scripts.
Thats all. Every time you run ‘rake sitemap:generate’, it generates a sitemap.xml in the Rails.root/public folder and sends it to the listed search engines.
NITHIN STANY — February 19, 2010
nice one … great work
Dan — March 4, 2010
thanks for this site map tutorial. I’m just having one problem getting it to work for my site. I’m trying to switch your articles model to a newsletters one, so it will map each newsletter that I have.
My sitemap.rb has
@pages_to_visit += Newsletter.all.collect{ |c| newsletter_path© }
the error when i run the rake is:
undefined method `newsletter_path’ for Sitemap:Class
Do you know how i get it to recognize that path?
my routes.rb doesn’t have any specified paths just
map.resources :newsletters
i obviously want it to be creating a site map entry for each newsletter’s show method.
Thanks for the help,
Dan
Bashar — June 21, 2010
Thanks. Just what I needed :)
Kinunt — August 23, 2010
I have the same problem as Dan, any ideas? I think post_path is not accesible from this method because post_path is a controller method and is not accesible from here.
Joe — January 27, 2011
If you are having problems with model_path method. Try this:
Use “app” in front of the method:
e.g:
@pages_to_visit += Video.all.collect{ |a| app.video_path(a) }
It works for me. Happy Coding :)
Taylor Brooks — June 14, 2011
I’m getting an error, any thoughts?
“uninitialized constant Sitemap”
Jason Green — June 14, 2011
have you added the sitemap.rb to your lib directory?
Web Tempest — September 21, 2011
Rails 3 doesn’t include the lib folder. You have to manually include it:
config.autoload_paths += Dir["#{config.root}/lib/**/"]
Rolando Alvarado — November 8, 2011
Nice work. Helps me a lot.
Alessandro Muraro — December 3, 2011
Hello, i get an error,
undefined method `article_path’ for Sitemap:Class
/home/alex/Documents/Web/MYSITE/Rakefile:12
i added the lib in application.rb but now have no clue why it’s not working… any hint?
Thanks a lot!