0

I have an array arr = ["model", "engine", "year", ................] where each element is an attribute name of Car model.
I am trying to push these specific attribute values to another array

Car.all.each do |mycar|
  another_array << arr.map{ |attr| mycar.attr }
end

This of course gives the expected no method error .attr for <object>. What is the correct way to do this ?? EDIT I know about .send() method but I found that some fields encrypted using attr-encrypted gem are not decrypted properly when I use .send(). So I have to try something else like this

2 Answers 2

2

You needn't anything Rails/ActiveRecord specific.

If you're sure the attributes are "safe" (that is, the users couldn't have meddled with the list, or you validated the method names before), you can simply use ruby's send:

mycar.send(attr) # dangerous
mycar.public_send(attr) # a bit less dangerous. Keep reading for the correct solution..

ActiveRecord does provide a shortcut for this, however (that does checking for you):

mycar[attr]
Sign up to request clarification or add additional context in comments.

5 Comments

yes I know, I have been using .send method but since I use attr-encrypted gem I found some fields are not decrypted when using send method, rthats why I have to try somthing like this
you'll need to store your list with encrypted_ before
then I won't get decrypted value
a.b and a.send(:b) are literally the same. Use the correct method name as described in attr-encrypted.
public_send is safer here.
0

You can make use of attributes

Car.all.each do |mycar|
  another_array << mycar.attributes.slice("model", "engine", "year").values }
end

1 Comment

Thanks for your help but I cant use .values because att-encrypted uses 'encrypted_' prefix before attributes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.