将globalize_accessor语言环境限制为来自控制器/视图的参数

时间:2015-10-24 00:13:10

标签: ruby-on-rails globalize3

我正在使用globalize_accessor gem来呈现具有:name字段的多语言输入的表单,并且希望限制用户可以根据哪些语言作为参数传递给{ {1}}方法。这样的事情可能吗?

这是我到目前为止所拥有的:

globalize_attribute_names

更新

据我所知,为转换定义语言环境的唯一方法是在模型级别显式传递它们。但是,当尝试使用方法来定义这些时,我看到一个未定义的局部变量或方法错误。我目前使用的方法是用于实验,理想的用例是使用此方法调用Chart的父级并为其返回可接受的语言。这是更新后的代码:

chart.rb

class Chart < ActiveRecord::Base
  belongs_to :chart_type
  belongs_to :section
  has_many :data_points, dependent: :destroy

  translates :name
  globalize_accessors :attributes => [:name]

  validates :name, presence: true

  accepts_nested_attributes_for :data_points
end


charts/new.html.haml

= simple_form_for chart,  html: {multipart: true} do |f|
  - Chart.globalize_attribute_names.each do |lang|
    = f.input lang
  = f.input :chart_type, collection: @chart_types
  = f.input :section, collection: @sections, label_method: :heading
  = f.simple_fields_for :data_points, chart.data_points.build do |c|
    = c.input :file, as: :file
  = f.submit

1 个答案:

答案 0 :(得分:1)

您看到一个未定义的局部变量或方法错误,因为您在类中使用它后定义了方法languages 。只需在globalize_accessors调用上方定义方法即可,您应该没问题:

class Chart < ActiveRecord::Base

  ...

  def self.languages # <= define this first
    [:en, :fr]
  end

  globalize_accessors :attributes => [:name], locales: languages