我有一个家长班:
class Address < ActiveRecord::Base
...
validates_presence_of :first_name
validates_presence_of :last_name
validates_presence_of :street_address
validates_presence_of :street_address2
validates_presence_of :zip_code
validates_presence_of :city
validates_presence_of :state_id
validates_presence_of :phone_number
end
还有两个子类:
class ShippingAddress < Address
end
class BillingAddress < Address
end
但是,当我在表单上创建无效记录时(一次创建两个记录),ShippingAddress和BillingAddress的验证错误是相同的,我不希望这样做:
First name can't be blank
First name can't be blank
Last name can't be blank
Last name can't be blank
Street address can't be blank
Street address can't be blank
Street address2 can't be blank
Street address2 can't be blank
Zip code can't be blank
Zip code can't be blank
City can't be blank
City can't be blank
Phone number can't be blank
Phone number can't be blank
我如何在验证错误前加上类名like "Shipping address first name can't be blank"
?
==更新==
尝试时Yoshi的答案无效:
class Address < ActiveRecord::Base
validates_presence_of :first_name, message: I18n.t("activerecord.errors.models.#{self.model_name.to_s.underscore}.attributes.first_name")
Nets-Mac-Pro:ilook emai$ be rails c
Loading development environment (Rails 4.1.1)
irb(main):001:0> s = ShippingAddress.new
=> #<ShippingAddress id: nil, first_name: nil, last_name: nil, street_address: nil, street_address2: nil, zip_code: nil, phone_number: nil, created_at: nil, updated_at: nil, state_id: nil, city: nil, type: "ShippingAddress", order_id: nil>
irb(main):002:0> s.valid?
=> false
irb(main):003:0> s.errors.full_messages
=> ["First name translation missing: en.activerecord.errors.models.address.attributes.first_name", "Last name can't be blank", "Street address can't be blank", "Street address2 can't be blank", "Zip code can't be blank", "City can't be blank", "State can't be blank", "Phone number can't be blank"]
它说模型名称是Address而不是ShippingAddress。我猜这是渴望加载。
Rails用于human_attribute_name
将属性名称转换为人类可读的形式。您可以尝试在中重写此类方法,ShippingAddress
并BillingAddress
避免必须在区域设置文件中指定每个验证消息。
class ShippingAddress < Address
def self.human_attribute_name(*args, &block)
"Shipping address #{ super }"
end
end
class BillingAddress < Address
def self.human_attribute_name(*args, &block)
"Billing address #{ super }"
end
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句