1

我有一个Department模型,其中我使用 Globalize gem::name:permalink.

:permalink是根据部门的:name,使用:before_validation回调自动生成的。

我希望名称和永久链接是强制性的,因此我在翻译类上添加了验证,而不是在迁移中添加了空约束。

class Department < ActiveRecord::Base
  translates :name, :permalink, fallbacks_for_empty_translations: true
  globalize_accessors

  before_validation :set_permalink, on: :create

  validates_associated :translations
  translation_class.validates :name, presence: true, length: { maximum: 255 }
  translation_class.validates :permalink, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }

  private

  def set_permalink
    I18n.available_locales.each do |l|
      I18n.with_locale(l) { self.permalink = name.to_url }
    end
  end
end

 

class CreateDepartment < ActiveRecord::Migration
  def up
    create_table :departments do |t|
      # other attributes

      t.timestamps null: false
    end

    Department.create_translation_table! name: { type: :string, null: false }, permalink: { type: :string, null: false, index: { unique: true } }
  end

  def down
    Department.drop_translation_table!
    drop_table :departments
  end
end

但是当我尝试创建部门时,验证失败:

irb(main):001:0> Department.create!(name_en: 'Tools', name_fr: 'Outils')
   (0.2ms)  BEGIN
  Department::Translation Exists (1.4ms)  SELECT  1 AS one FROM "department_translations" WHERE "department_translations"."permalink" IS NULL LIMIT 1
  Department::Translation Exists (0.3ms)  SELECT  1 AS one FROM "department_translations" WHERE "department_translations"."permalink" IS NULL LIMIT 1
  Department::Translation Exists (0.4ms)  SELECT  1 AS one FROM "department_translations" WHERE "department_translations"."permalink" IS NULL LIMIT 1
  Department::Translation Exists (0.3ms)  SELECT  1 AS one FROM "department_translations" WHERE "department_translations"."permalink" IS NULL LIMIT 1
   (0.2ms)  ROLLBACK
ActiveRecord::RecordInvalid: Validation failed: Translations permalink can't be blank, Translations is invalid

但是,如果我删除了永久链接的验证和非空约束,则可以保存部门并且所有翻译都存在永久链接。

我不明白为什么验证失败...如何设置验证和永久链接的自动生成,以便它们一起工作?

我正在使用带有 Globalize 5 的 Rails 4.2.5。

4

0 回答 0