7

次のように、Rails アプリに ActiveModel クラスを設定しました。

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 を書くこともできますが、どこかに存在するような気がします。そうですか?

4

2 に答える 2

7

いいえ、しかし、この場合には一般的なパターンがあります:

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

ここからです。例については、リンクを参照してください。

このアプローチを頻繁に繰り返す場合は、このメソッドを別のモジュールに抽出し、必要に応じて含めることができます。

于 2012-06-11T07:03:00.117 に答える
0

アクティブなレコードから引き抜いて、Rails 5 のアクティブなモデルに移動したようです。

http://api.rubyonrails.org/classes/ActiveModel/AttributeAssignment.html#method-i-assign_attributes

モジュールを含めることができるはずです:

include ActiveModel::AttributeAssignment
于 2016-09-30T19:55:49.063 に答える