ruby-on-rails - ActiveModel 是否有包含 "update_attributes"方法的模块?

标签 ruby-on-rails ruby-on-rails-3 activemodel

我在 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.请参阅链接以获取示例。

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

关于ruby-on-rails - ActiveModel 是否有包含 "update_attributes"方法的模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10975370/

相关文章:

ruby-on-rails - ActiveModel:验证相等性的值

ruby-on-rails - 如何使用事件模型为 date_select 下拉菜单定义虚拟属性

javascript - 卡住整个网站的音乐播放器

ruby-on-rails - fullCalendar 的集成测试

ruby-on-rails - 带有设计的用户个人资料页面 - 显示操作的路由

mysql - Mac OS 10.6 服务器无法安装 mysql gem

ruby-on-rails - Mongoid::Errors::MixedRelations + 保存

ruby-on-rails - Rails、设计和 Haml : syntax error, 意外 kELSE

ruby-on-rails-3 - Rails3 : Avoiding select n+1 with the Ancestry Gem?

ruby-on-rails - 不能包含 ActiveModel::Model