开发者

How to validate presence on model with specific field

开发者 https://www.devze.com 2023-01-30 00:35 出处:网络
How can I update all fields in table where the开发者_JS百科 record value is null with validate_presence_of without write all fields one by one? You mean like default values? Easiest way is to set defa

How can I update all fields in table where the开发者_JS百科 record value is null with validate_presence_of without write all fields one by one?


You mean like default values? Easiest way is to set defaults in your database

add_column :posts, :excerpt, :text, :default => "No excerpt available"

validates_presence_of only checks if a value is present or not.

Optionally, you can set a before_validation hook:

before_validation :set_values

def set_values
  attributes.each do |attr|
    self.send("#{attr}=".to_sym, 'Default value') if attr.nil?
  end
end


I don't think you can use validations for that purpose. Validations are only run when an object is somehow saved or updated to the database so if you already have a bunch of records in a table and then write a validation afterwards, it will not affect the existing database records at all. Unless you try to update them again.

However, if you want to update a bunch of records with one database query them you can use a method call update_all. It could look something like this:

Record.update_all "value = 'default_value'", "value IS NULL"
0

精彩评论

暂无评论...
验证码 换一张
取 消