2012-06-11 5 views
7

私はこのように私のRailsアプリでActiveModelクラスを設定している:私は本当にこれを行うことができるようにしたいActiveModelには「update_attributes」メソッドを含むモジュールがありますか?

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 

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

私はちょうど自分でupdate_attributesを書くことができ、私はそれがどこかに存在すると感じています。それは?

答えて

7

ありませんが、この場合の一般的なパターンがあります:それはfrom here.

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 

は例のリンクを参照してください。

この方法を頻繁に繰り返す場合は、この方法を別のモジュールに抽出し、必要に応じて組み込むことができます。

+0

がありますより新しいレールバージョンの啓示はまだありますか? – schmijos

関連する問題