url中的locale前缀

时间:2011-09-06 09:02:29

标签: ruby-on-rails ruby-on-rails-3

在我的Rail 3.0.9应用程序中,我有routes.rb:

Myapp::Application.routes.draw do
  root :to => 'index#index'
  match '/:locale' => 'index#index', :locale => /ru|en/
  scope "(:locale)", :locale => /ru|en/ do
    resources :pages, :only => [:show]
...

在浏览器中转到/ path时,会显示404错误并在日志中显示消息:

Started GET "/" for 127.0.0.1 at Tue Sep 06 12:45:18 +0400 2011
  Processing by IndexController#index as HTML
Creating scope :limit. Overwriting existing method NewsItem.limit.
  ESC[1mESC[35mNewsItem Load (0.2ms)ESC[0m  SELECT `news_items`.* FROM `news_items` WHERE (category = 'events') ORDER BY published_at DESC
Rendered layouts/_mini_calendar.erb (29.5ms)
  ESC[1mESC[36mSQL (0.2ms)ESC[0m  ESC[1mSELECT COUNT(*) FROM `news_items` WHERE (category = 'events') AND (published_at BETWEEN '2010-12-31 21:00:00' AND '2011-01-01 20:59:59')ESC[0m
  ESC[1mESC[35mSQL (0.2ms)ESC[0m  SELECT COUNT(*) FROM `news_items` WHERE (category = 'events') AND (published_at BETWEEN '2010-12-31 21:00:00' AND '2011-01-31 20:59:59')
  ESC[1mESC[36mNewsItem Load (0.2ms)ESC[0m  ESC[1mSELECT `news_items`.* FROM `news_items` WHERE (category = 'events') ORDER BY published_at DESC LIMIT 3ESC[0m
Rendered index/index.html.erb within layouts/static (212.4ms)
Completed 500 Internal Server Error in 220ms
No route matches {:locale=>#<NewsItem id: 20, title_ru: "event 2", description_ru: "<p>event description</p>", published_at: "2011-08-31 07:55:00", category: "events", created_at: "2011-08-31 07:55:26", updated_at: "2011-08-31 07:55:26", short_description_ru: "<p>descr</p>", title_en: nil, description_en: nil, short_description_en: nil>, :action=>"show", :controller=>"news_items"}
Rendered layouts/_head_static.erb (2.3ms)
Rendered layouts/_ga.erb (0.3ms)
Rendered layouts/_logo.erb (1.0ms)
Rendered layouts/_copiny_widget.erb (0.3ms)
Rendered errors/404.html.erb within layouts/error (10.6ms)

它试图让奇怪的链接

No route matches {:locale=>#<NewsItem id: 20, title_ru: "event 2", description_ru: "<p>event description</p>", published_at: "2011-08-31 07:55:00", category: "events", created_at: "2011-08-31 07:55:26", updated_at: "2011-08-31 07:55:26", short_description_ru: "<p>descr</p>", title_en: nil, description_en: nil, short_description_en: nil>, :action=>"show", :controller=>"news_items"}

问题在于

<%= link_to l(news_item.published_at, :format => "%d.%m.%Y"), news_item %>

当我将其更改为

<%= link_to l(news_item.published_at, :format => "%d.%m.%Y"), :url => news_item %>

问题解决了。

1)为什么第一行的news_item被解释为:locale,而不是:url?

2)这是一个错误还是我错过了什么?

感谢所有人!

最后我找到了最佳解决方案:

def set_locale
  ...
  self.default_url_options[:locale] = params[:locale]
end

1 个答案:

答案 0 :(得分:2)

要解决这个问题,我们可以这样做:

def set_locale
  ...
  self.default_url_options[:locale] = params[:locale]
end