sitemap_generator gem 创建 UrlGenerationError

sitemap_generator gem creates UrlGenerationError

我使用(除其他外):

gem 'rails', '4.0.0'
gem 'sitemap_generator', '3.4'
gem "friendly_id", "~> 5.0.3"
gem 'globalize', '~> 4.0.2'

站点地图生成器应该为我的所有图片创建 url:

class Image < ActiveRecord::Base
  attr_accessible :description, :name, :size, :image, 
                  :tag_ids, etc...

  has_many :taggings, :dependent => :destroy
  has_many :tags, :through => :taggings
  has_and_belongs_to_many :articles
  mount_uploader :image, ImageUploader
  extend FriendlyId
  friendly_id :name, use: [:slugged, :history]
  translates :name, :description
end

我的站点地图生成器通常运行良好,但不适用于图像模型。相关代码为:

[nil, :de].each do |locale|
  Image.find_each do |image|
    sitemap.add image_path(image), :changefreq => 'monthly'
  end
end

现在,当我做耙子时 sitemap:refresh:no_ping

ActionController::UrlGenerationError: 没有路由匹配 {:action=>"show", :controller=>"images", :locale=>#, :id=>nil, :format=> nil} 缺少必需的键:[:id]

我认为您可能需要更多信息来提供帮助,但我不知道是什么。该网站以两种语言运行良好,rake:routes 给出:

images GET (/:locale)/images(.:format)       images#index {:locale=>/en|de/}
POST (/:locale)/images(.:format)             images#create {:locale=>/en|de/}
new_image GET  (/:locale)/images/new(.:format)  images#new {:locale=>/en|de/}
edit_image GET (/:locale)/images/:id/edit(.:format) images#edit {:locale=>/en|de/}
image GET (/:locale)/images/:id(.:format)    images#show {:locale=>/en|de/}
PATCH  (/:locale)/images/:id(.:format) images#update {:locale=>/en|de/}
PUT (/:locale)/images/:id(.:format) images#update {:locale=>/en|de/}
DELETE (/:locale)/images/:id(.:format) images#destroy {:locale=>/en|de/}

最后我的 routes.rb 是:

scope "(:locale)", locale: /en|de/ do
  resources :images do
    get 'confirm_destroy', :on => :member
  end
end

问题是我必须在 sitemap.rb 中传递语言环境。所以 sitemap.rb 中的正确代码是:

image = Image.all

[nil, :de].each do |locale|
  image.find_each do |image|
    sitemap.add image_path(image, :locale => locale)
  end
end

生成 SiteMap 真的很简单 以下是您需要知道的事情

1) 路线

  #config/routes.rb
  get 'sitemap.xml', :to => 'sitemap#index', :defaults => {:format => 'xml'}
  root '...'

2) 控制器

#app/controllers/sitemap_controller.rb
class SitemapController < ApplicationController
  layout nil
  def index
    headers['Content-Type'] = 'application/xml'
    respond_to do |format|
      format.xml {
        @images = Image.all
      }
    end
  end
end

3) 现在的视图我用的是haml

#app/views/sitemap/index.xml.haml
!!! XML
%urlset{:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9"}
  - @images.each do |image|
    %url
      %loc #{image_url(image)}
      %lastmod=image.updated_at.strftime('%Y-%m-%d')
      %changefreq weekly
      %priority 0.5

创建站点地图没有别的了

希望对您有所帮助:)