ActiveModel是否有包含"update_attributes"方法的模块?

Bra*_*ugh 7 ruby-on-rails activemodel ruby-on-rails-3

我在我的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
Run Code Online (Sandbox Code Playgroud)

我真的希望能够做到这一点:

thingy = MyThingy.new(params)
thingy.update_attributes(:favorite_color => :red, :stuff => 'other stuff')
Run Code Online (Sandbox Code Playgroud)

我可以自己编写update_attributes,但我觉得它存在于某个地方.可以?

jdo*_*doe 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
Run Code Online (Sandbox Code Playgroud)

来自这里.请参阅链接以获取示例.

如果您发现自己经常重复此方法,则可以将此方法提取到单独的模块中并包括按需包含它.