使用 ActiveRecord 对象,您可以使用 .assign_attributes 或更新
方法:
user.assign_attributes( name: "abc", email: "abc@test.com", mobile: "12312312")
# attributes= is a shorter alias for assign_attributes
user.attributes = { name: "abc", email: "abc@test.com", mobile: "12312312" }
# this will update the record in the database
user.update( name: "abc", email: "abc@test.com", mobile: "12312312" )
# or with a block
user.update( name: "abc", mobile: "12312312" ) do |u|
u.email = "#{u.name}@test.com"
end
.update 接受一个块,而 assign_attributes 不接受。如果您只是分配文字值的哈希值 - 例如用户在参数中传递的值,则无需使用块。
如果你有一个普通的旧红宝石对象,你想通过批量赋值来增加趣味,你可以这样做:
class User
attr_accessor :name, :email, :mobile
def initialize(params = {}, &block)
self.mass_assign(params) if params
yield self if block_given?
end
def assign_attributes(params = {}, &block)
self.mass_assign(params) if params
yield self if block_given?
end
def attributes=(params)
assign_attributes(params)
end
private
def mass_assign(attrs)
attrs.each do |key, value|
self.public_send("#{key}=", value)
end
end
end
这会让你做:
u = User.new(name: "abc", email: "abc@test.com", mobile: "12312312")
u.attributes = { email: "abc@example.com", name: "joe" }
u.assign_attributes(name: 'bob') do |u|
u.email = "#{u.name}@example.com"
end
# etc.