我正在使用gem: globalize3和easy_globalize3_accessors。我有一个关于验证的问题。例如,我有Post模型:
class Post
translates :title, :content
globalize_accessors :locales => [:en, :ru], :attributes => [:title, :content]
validates :title, :content, :presence => true
end和表格:
= form_for @post do |f|
-I18n.available_locales.each do |locale|
= f.text_field "title_#{locale}"
= f.text_area "content_#{locale}"它看起来像是在视图中(如果I18n.locale = :ru):
<form action="/ru/posts" method="post">
<input id="post_title_ru" name="post[title_ru]" type="text" />
<textarea cols="40" id="post_content_ru" name="vision[content_ru]"></textarea>
<input id="post_title_en" name="post[title_en]" type="text" />
<textarea cols="40" id="post_content_en" name="vision[content_en]"></textarea>
<input name="commit" type="submit" value="Создать Видение" />
</form>如果我只用俄语填写字段,则验证通过;如果我想只用英语发帖,并且只填写英语字段(当I18n.locale =:ru时),则验证失败
Title can't be blank
Content can't be blank据我所知,属性中有一个问题,验证只检查第一个属性:title_ru和:content_ru。而对于其余的属性(:content_en和:title_en),则无法进行检查。
如何让第二个数据验证器检查第一组属性的验证是否未通过?
提前感谢
发布于 2012-08-29 22:04:47
validate :titles_validation
def titles_validation
errors.add(:base, "your message") if [title_ru, title_en].all? { |value| value.blank? }
end发布于 2012-08-29 21:49:10
问题是,globalize3正在为您当前所在的任何语言环境验证标题。如果你想验证每个语言环境(不仅仅是当前的语言环境),你必须显式地为每个语言环境中的属性添加验证器(正如@apneadiving指出的那样)。
您应该能够通过遍历I18n.available_locales来自动生成这些验证器
class Post < ActiveRecord::Base
I18n.available_locales.each do |locale|
validates :"title_#{locale}", :presence => true
end
...
endhttps://stackoverflow.com/questions/12178428
复制相似问题