ruby-on-rails – ActiveModel是否有一个包含“update_attributes”方法的模块?

我在我的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,但我觉得它存在于某个地方.可以?

解决方法

不,但这种情况有共同的模式:
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

它是from here.请参阅链接获取示例.

如果您经常重复此方法,则可以将此方法提取到单独的模块中,并根据需要包含它.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...