2012-06-11 28 views
7

tôi đã thiết lập một lớp ActiveModel trong ứng dụng Rails của tôi như thế này:ActiveModel có mô-đun bao gồm phương thức "update_attributes" không?

class MyThingy 
    extend ActiveModel::Naming 
    extend ActiveModel::Translation 
    include ActiveModel::Validations 
    include ActiveModel::Conversion 

    attr_accessor :username, :favorite_color, :stuff 

    def initialize(params) 
    #Set up stuff 
    end 

end 

Tôi thực sự muốn để có thể làm điều này:

thingy = MyThingy.new(params) 
thingy.update_attributes(:favorite_color => :red, :stuff => 'other stuff') 

tôi chỉ có thể viết update_attributes trên của riêng tôi, nhưng tôi có cảm giác nó tồn tại ở đâu đó. Phải không?

Trả lời

7

Không, nhưng có mẫu chung cho trường hợp này:

class Customer 
    include ActiveModel::MassAssignmentSecurity 

    attr_accessor :name, :credit_rating 

    attr_accessible :name 
    attr_accessible :name, :credit_rating, :as => :admin 

    def assign_attributes(values, options = {}) 
    sanitize_for_mass_assignment(values, options[:as]).each do |k, v| 
     send("#{k}=", v) 
    end 
    end 
end 

Đó là from here. Xem liên kết cho ví dụ.

Nếu bạn thấy mình lặp lại phương pháp này thường xuyên, bạn có thể trích xuất phương thức này thành một mô-đun riêng biệt và bao gồm đưa vào theo yêu cầu.

+0

Có bất kỳ giác ngộ cho các phiên bản ray mới hơn chưa? – schmijos

Các vấn đề liên quan