Rails验证错误消息,自定义属性名

时间:2022-10-10 12:19:53

If a model has an attribute named "unit" for example, but in your views you refer to this attribute as "unit price", but when you do validation, error messages default to "unit", how do I modify this to say "unit price"?

例如,如果一个模型有一个名为“unit”的属性,但是在您的视图中,您将该属性称为“单价”,但是当您进行验证时,错误消息默认为“unit”,那么我如何将其修改为“单价”呢?

2 个解决方案

#1


2  

Use localization to set the "English" name of your attribute. You can set both the singular and plural names:

使用本地化设置属性的“English”名称。你可以同时设定单数和复数名称:

en:
  activerecord:
    attributes:
      product:
        unit:
          one:   Unit price
          other: Unit prices

#2


1  

I'm not sure how you can change the column name , But following is a working workaround

我不确定如何更改列名,但是下面是一个可行的解决方案

in your model create a virtual attribute called unit_price

在模型中创建一个名为unit_price的虚拟属性

something like this

像这样的东西

attr_accessor :unit_price

validates_presence_of :unit_price, :message => "This is a custom validation message"

def before_validation
   self.unit_price = self.unit
end

cheers

干杯

sameera

sameera

#1


2  

Use localization to set the "English" name of your attribute. You can set both the singular and plural names:

使用本地化设置属性的“English”名称。你可以同时设定单数和复数名称:

en:
  activerecord:
    attributes:
      product:
        unit:
          one:   Unit price
          other: Unit prices

#2


1  

I'm not sure how you can change the column name , But following is a working workaround

我不确定如何更改列名,但是下面是一个可行的解决方案

in your model create a virtual attribute called unit_price

在模型中创建一个名为unit_price的虚拟属性

something like this

像这样的东西

attr_accessor :unit_price

validates_presence_of :unit_price, :message => "This is a custom validation message"

def before_validation
   self.unit_price = self.unit
end

cheers

干杯

sameera

sameera