根据另一个人的存在来验证一个字段

时间:2013-04-02 09:32:04

标签: ruby-on-rails ruby-on-rails-3 validation

我有两个字段:

attr_accessible :in_home #=> boolean, setted at false by default
mount_uploader :carousel_picture, CarouselUploader#=>an image picture with CarrierWave + Rmagick. Nil by default
attr_accessible :carousel_picture

我的问题是:我尝试验证当用户选中“in_home”复选框时,他应该已经上传了“carousel_picture”

    validates :in_home, :if => Proc.new { |obj| (obj.in_home && obj.carousel_picture?) == true }, :presence => {:message => "You should upload a carousel picture to set the item in the home page."},

但是这个验证不起作用,我可以创建一个对象,其中检查了in_home并且carousel_picture为空。

当我在rails控制台中尝试时:

1.9.3p362 :001 > obj = MyObject.all.last
  => #<Gift id: 22, name: "foo", created_at: "2013-04-02 09:13:00", updated_at: "2013-04-02 09:13:00", carousel_picture: nil, in_home: true>
1.9.3p362 :002 > obj.in_home && obj.carousel_picture?
  => false 

所以我认为我对如何验证字段有些不明白。任何帮助都会有用! 提前谢谢

2 个答案:

答案 0 :(得分:1)

试试这个,

validates_presence_of :carousel_picture, :if => lambda {|obj| obj.in_home == true}

答案 1 :(得分:1)

我最近尝试做类似的事情,我认为下面的代码应该适合你:

validates :carousel_picture, :presence => { :if => Proc.new { |a| a.in_home? }, message: "You should upload a carousel picture to set the item in the home page." }