开发者

how to create a new hash collection from a model collection

开发者 https://www.devze.com 2023-03-26 07:14 出处:网络
I have a collection of model objects that I need to convert into another collection but with many of the model\'s attributes removed.

I have a collection of model objects that I need to convert into another collection but with many of the model's attributes removed.

Other than me looping through the existing collection and creating a new collection, is there a better way?

Say I have a user model like:

User id, name, password, country, city

And 开发者_开发知识库I want to create a new collection with the User model but with only the attributes: id, name, country

What's the best way to do this?


The .select method will only fetch the specified fields for the object:

users = User.select([:id, :name, :country])

So users is an array of all User objects with only id, name and country populated. Is that what you need?

0

精彩评论

暂无评论...
验证码 换一张
取 消