2014-08-28 42 views

回答

2

如果这是ActiveRecord的对象,然后:

user.assign_attributes(
    first_name: "first" 
    last_name: "last" 
    email: "[email protected]" 
) 
2

什么blockActiveRecord有这么多的方法:

User.new.tap do |user| 
    user.name  = "John Doe" 
    user.username = "john.doe" 
    user.password = "john123" 
end 

或:

User.new do |user| 
    user.name  = "John Doe" 
    user.username = "john.doe" 
    user.password = "john123" 
end 

或混合的initialize:

User.new(name: "John Doe") do |user| 
    user.username = "john.doe" 
    user.password = "john123" 
end 

或超简单与update()

user.update(
    first_name: "first" 
    last_name: "last" 
    email: "[email protected]" 
) 
+0

'tap'是不是从'ActiveRecord' http://ruby-doc.org/core-2.1.2/Object.html#method-i-tap – IS04 2014-08-28 11:31:42

+0

@ IS04我知道这件事。我不会说'tap'只能在'AR'中使用 – 2014-08-28 11:33:19

0

非ActiveRec奥德可以使用instance_eval的方法,如:

class SomeClass 
    def a(*args) 
    @a ||= args 
    end 

    def b(*args) 
    @b ||= args 
    end 
end 

2.0.0 (main):0> some_class_instance = SomeClass.new 
=> #<SomeClass:0x007f9b62b629c0> 
2.0.0 (main):0 > s = "a 'a args' 
2.0.0 (main):0 * b 'b args'" 
=> "a 'a args'\nb 'b args'" 

2.0.0 (main):0 > some_class_instance.instance_eval(s) 
=> ["b args"] 
2.0.0 (main):0 > some_class_instance.a 
=> ["a args"] 
2.0.0 (main):0 > some_class_instance.b 
=> ["b args"]