2

我正在尝试为我的路线做一个简单的语言翻译,但我真的不明白为什么我的方法不起作用。我想www.example.com/it/camere打电话rooms_path(locale: :it)www.example.com/en/rooms打电话rooms_path(locale: :en)
例如,查看以下路线:

get ":locale/rooms" => "home#rooms", constraints: { locale: "en" }, as: "rooms"
get ":locale/camere" => "home#rooms", as: "rooms"

我得到以下结果:

app.rooms_path               # => error         OK
app.rooms_path(locale: "it") # => 'it/camere'   OK
app.rooms_path(locale: "en") # => 'en/camere'   Why?!?

并使用以下路线(注意第二个约束):

get ":locale/rooms" => "home#rooms", constraints: { locale: "en" }, as: "rooms"
get ":locale/camere" => "home#rooms", constraints: { locale: "it" }, as: "rooms"

我得到以下结果:

app.rooms_path               # => error         OK
app.rooms_path(locale: "it") # => 'it/camere'   OK
app.rooms_path(locale: "en") # => error         Lol?!? This is weird!

有人可以向我解释为什么会这样吗?
我已经阅读了大约 3 次关于路由的 Rails 文章,但它没有帮助。

PS我宁愿不使用插件来学习:)

编辑:

这是我通过调用 rake 路由得到的:

rooms GET    /:locale/rooms(.:format)    home#rooms {:locale=>"en"}
rooms GET    /:locale/camere(.:format)   home#rooms {:locale=>"it"}
root         /(:locale)(.:format)        home#index
4

1 回答 1

0

关于第一种情况

您不能使用:as相同的名称使用两次。第二次使用它会替换之前的xxx_path定义,你最终会得到没有约束的rooms_pathwhich 指向。:locale/camere看起来你高估了 Rails 的魔力。

关于第二种情况

get ":locale/camere" => "home#rooms", constraints: { locale: "it" }, as: "rooms"

调用失败,app.rooms_path(locale: "en")因为只有一个rooms_path可用并且它期望:locale"it". 调用它"en"自然会导致未解决的路由抱怨。

如果您想查看其来源,请查看define_url_helper

于 2012-07-25T18:44:56.690 回答