简体   繁体   English

Rails:使用 form_with 的语言环境?

[英]Rails: Locales using form_with?

How do I use locales and form_with ?我如何使用 locales 和form_with By locale I mean /en instead of /?locale=en .语言环境我的意思是/en而不是/?locale=en

This is part of my view file:这是我的视图文件的一部分:

<%= form_with(model: @model, local: true, locale: I18n.locale) do |form| %>

After submitting the form I get the following error:提交表单后,我收到以下错误:

No route matches {:action=>"show", :controller=>"model_name", :format=>nil, :locale=>#<ModelName id: 2, created_at: "2018-10-15 11:07:36", updated_at: "2018-10-15 11:08:09">}, missing required keys: [:id], possible unmatched constraints: [:locale]

Notice how locale is set with the given model ...请注意如何使用给定模型设置语言环境...

This is my routes.rb :这是我的routes.rb

root 'model_name#new'

scope ':locale', locale: /[a-z]{2}/ do
  root 'model_name#new'
  resources :model_name, only: [:create, :show]
end

I don't understand why I need to set root twice but ...我不明白为什么我需要设置 root 两次但是......

Thanks!谢谢!

root inside of scope means the root of the scope. root的范围内是指范围的根。

Example:例子:

root # matches / 
scope ':locale' do
  root # matches /en/
  resources :foos # matches /en/foos, /en/foo/1, ...
end

I suggest you to call rake routes to see what routes you have defined and play around a bit.我建议你调用rake routes来看看你定义了哪些路由并稍微玩一下。

And back to the error you are getting.回到你得到的错误。 This error means, that the constraint on the scope is not matched.此错误意味着范围的约束不匹配。 I'd bet, that the locale is empty.我敢打赌,语言环境是空的。 according to docs of form_with , you should use scope option, like this:根据form_with 文档,您应该使用 scope 选项,如下所示:

<%= form_with(model: @model, local: true, scope: I18n.locale) do |form| %>

Rails is using your instance of ModelName because locale isn't set. Rails 正在使用您的 ModelName 实例,因为未设置语言环境。 To be sure that your locale is set in urls, add the default_url_options method to application_controller , where set_locale contains the logic for your application's locale.要确保在 urls 中设置了语言环境,请将default_url_options方法添加到application_controller ,其中set_locale包含应用程序语言环境的逻辑。

def default_url_options
   { locale: set_locale }
end

private def set_locale
  params[:locale] || I18n.default_locale
end

source: https://guides.rubyonrails.org/i18n.html#managing-the-locale-across-requests来源: https : //guides.rubyonrails.org/i18n.html#managing-the-locale-across-requests

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM