Rails 3 with composed_of model and validation

ぃ、小莉子 提交于 2019-12-05 23:08:22

When you define a composed_of attribute, it becomes an object on it's own. I see two ways to answer your need.

1) add error message in your Address class

Replace your current validations with:

validates_each :street, :city, :zip_code, :country do |record, attr, value|  
  record.errors.add attr, 'should not be blank' if value.blank?
end

This way, you'll be able to access the error messages doing:

p = Person.new
p.address.errors

2) Customize only the address error message

validates_associated  :address, 
                      :message => lambda { |i18n_key, object| self.set_address_error_msg(object[:value]) }

def self.set_address_error_msg address
  errors_array = Array.new
  address.instance_variables.each do |var|
    errors_array << "#{var[1..-1]} should not be blank" if address.send(var[1..-1]).blank?
  end
  errors_array.join(", ")
end       

This would render something like:

=> #<OrderedHash {:address=>["country should not be blank, zip_code should not be blank, validation_context should not be blank, city should not be blank"]}> 

Finally, you could rewrite validators in your Profile class but as you said it's really ugly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!