从ruby中的对象中删除不需要的属性
我有一个对象具有来自调用db的所有属性,让我们说:
u = User.find_by_email("email@email.com")
你有first_name
, last_name
, email
, phone
等。
如何从对象本身获取除first_name
和last_name
之外的所有属性,而不是通过修改对模型的调用?
u.attributes.except("first_name", "last_name")
选择您想要的属性可能更具前瞻性:
u.attributes.slice('email', 'phone')
如果您的类没有attributes
方法:
u.remove_instance_variable('@first_name') u.remove_instance_variable('@last_name')
如果您不想修改原始对象,可以复制该对象:
u_copy = u.dup u_copy.remove_instance_variable('@first_name') u_copy.remove_instance_variable('@last_name')
- 使用Ruby / Chef Recipe for Vagrant导入Mysql数据库
- ruby中的相同程序如何接受来自用户的输入以及命令行参数
- Ruby:寻找ruby-embeddable解释器或脚本语言
- 活动模型禁止属性错误
- Bootstrap不会加载rails和sass
- CKEditor 4:未捕获的TypeError:无法读取null的属性’langEntries’
- 从SQL Server 2008解析CSV的语义正确方法是什么?
- MongoDB和Mongoid正在制作中
- Ruby on Rails 3 + Apache2 + Phusion Passenger:Bundler :: GemNotFoundexception