Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The right way to remove attribute from rails model object

There is phone attribute in customer model with our rails 3.2.12 app. We would like to remove the phone attribute sometime when retrieving customers. Here is what we did:

@customers = Customer.all
@customers.delete :phone

However there is error:

delete_all doesn't support limit scope

What's the right way to remove an attribute from a model object? Thanks.

like image 720
user938363 Avatar asked Nov 25 '25 16:11

user938363


1 Answers

You can use Customer.select('name, address') to retrieve only the fields you want. Noting that you pass a string with comma separated field named.

This will generate an SQL request like this

SELECT customer.name, customer.address FROM customer

You then get only the data you want without deleting it from the database (which is what your original call is trying to do).

My original response showed incorrect use of pluck, which only works for a single column.

like image 126
muttonlamb Avatar answered Nov 28 '25 11:11

muttonlamb