我在我的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.请参阅链接以获取示例.
如果您经常重复此方法,则可以将此方法提取到单独的模块中,并根据需要包含它.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。