我想在保存到我的Rails应用程序之前验证数据。 如果数据不符合验证标准,则不会保存,用户也不会被警告。保存之前的非阻塞数据验证
其实我有这样的担心模型文件:
class Product < ActiveRecord::Base
belongs_to :content
before_validation :strip_whitespace
private
def strip_whitespace
self.label = self.label.strip
self.price = self.price.strip
end
end
我已经试过这样的事情在我的其他模型:
class Content < ActiveRecord::Base
belongs_to :user
has_many :products, :dependent => :destroy
accepts_nested_attributes_for :products, :reject_if => :all_blank
end
[编辑]
我终于将此行更改为:
class Content < ActiveRecord::Base
belongs_to :user
has_many :products, :dependent => :destroy
accepts_nested_attributes_for :products, :reject_if => proc {|attributes|
attributes['label'].blank?
attributes['price'].blank?
attributes['img_src'].blank?
attributes['link'].blank?
}
end
它的工作! 但是还有另一种解决方案,列出空白属性?条件?
尝试从控制台运行的代码,并张贴。 – Ashish 2011-03-14 12:04:59