0

我有 2 个字段:

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 

所以我认为在我如何验证一个字段时有些东西我不明白。任何帮助都会很有用!先感谢您

4

2 回答 2

1

试试这个,

validates_presence_of :carousel_picture, :if => lambda {|obj| obj.in_home == true}
于 2013-04-02T09:56:50.130 回答
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." } 
于 2013-04-02T10:01:23.550 回答