使用 Active Record 的 update 和 update_attributes 方法,并在更新前对属性值进行校验和过滤
示例代码:
class User < ActiveRecord::Base validates :email, presence: true, length: { maximum: 255 }, format: { with: /\A[\w+-.]+@[a-z\d-.]+.[a-z]+\z/i } before_update :normalize_name
private
def normalize_name self.name = name.capitalize end end
user = User.find(1) user.update(email: 'new_email@example.com')
user = User.find(1) user.update_attributes(name: 'new_name', email: 'new_email@example.com')