Ruby on rails 将语言从:de更改为:en时为nil类,但不是相反
我在Rails应用程序中使用翻译内容。当我将语言从默认语言:en更改为:de时,一切正常,但当我想将语言从:de更改为:en时,我得到一个Ruby on rails 将语言从:de更改为:en时为nil类,但不是相反,ruby-on-rails,ruby-on-rails-4,globalize3,Ruby On Rails,Ruby On Rails 4,Globalize3,我在Rails应用程序中使用翻译内容。当我将语言从默认语言:en更改为:de时,一切正常,但当我想将语言从:de更改为:en时,我得到一个NoMethodError(未定义的方法'color'表示nil:NilClass) 我做了一些研究并尝试了一些方法,但不得不承认我不完全理解这一点,这可能是错误的原因: application_controller.rb def set_locale I18n.locale = params[:locale] || I18n.default_local
NoMethodError(未定义的方法'color'表示nil:NilClass)
我做了一些研究并尝试了一些方法,但不得不承认我不完全理解这一点,这可能是错误的原因:
application_controller.rb
def set_locale
I18n.locale = params[:locale] || I18n.default_locale
request.subdomain
request.env["HTTP_ACCEPT_LANGUAGE"]
request.remote_ip
end
def default_url_options(options = {})
(I18n.locale.to_sym.eql?(I18n.default_locale.to_sym) ? {} : {locale: I18n.locale})
end
如果您能给我一个如何解决这个问题的提示,或者解释一下这个代码是如何工作的,我将不胜感激
模型如下:
page.rb
class Page < ActiveRecord::Base
translates :name, :permalink
validates_uniqueness_of :permalink, :message => "This url is already taken"
validates_presence_of :permalink
validates_presence_of :name
validates_format_of :permalink, :with => /\A[a-zA-Z0-9-_]*\z/i, :message => 'Url can only contain downcase letters from a-z and numbers from 0-9 and a dash and underscore'
before_save :only_allow_one_home_page
belongs_to :label
has_many :chapters
accepts_nested_attributes_for :chapters, :allow_destroy => true
mount_uploader :backgroundimage, BackgroundimageUploader
def chapters_for_form
collection = chapters.where(page_id: id)
collection.any? ? collection : chapters.build
end
def to_param
permalink
end
end
路线如下:
resources :labels, do
resources :pages
end
尝试将
链接更改为以下内容:
<%= link_to 'E', params.merge(locale: "en") %>
现在,回到错误。您必须为指向帮助程序的链接提供URL参数。您只提供“locale”,但它应该以某种方式确定您希望链接指向的页面。通过添加params.merge(locale:en)
我们指示它使用当前参数(因此它将链接到当前页面),只需向其添加locale
参数。您确切何时获得NoMethodError
?在一些请求之后(哪一个)?当您在控制台中执行某些操作时(具体是什么)?我在将语言从:de更改为:en时,通过单击链接得到错误信息:
欢迎您!如果你喜欢我的答案,也考虑一下投票:
<%= link_to 'E', params.merge(locale: "en") %>
# You must have `before_action :set_locale` somewhere in your controllers
# So, this method is called before your controller code does its job
def set_locale
# This just sets current locale to params[:locale]
# So when you request URL like http://example.org/controller/action?locale=de,
# params[:locale] contains 'de'
I18n.locale = params[:locale] || I18n.default_locale
end
# default_url_options is function which, well, adds default options
# to every call of url_for helper method
# It is also called internally when you build paths and urls for
# resources, like 'labels_path' or 'pages_url'
def default_url_options(options = {})
# This line just says to add 'locale=...' parameter (locale: I18n.locale) to the request,
# unless default locale is selected
# This will preserve your locale between requests
(I18n.locale.to_sym.eql?(I18n.default_locale.to_sym) ? {} : {locale: I18n.locale})
end