Alessandro, this issue of yours is complicated and requires us to understand some things:
1) If you want to return an object without the attribute id
, Rails won’t do it, and I’ll explain why:
You created a class, the model ActiveRecord
which is implicitly linked to the bank records. As in Rails everything is by convention, it admits that its class declares the attributes referring to the fields in the table to which it is bound. And we know that every object generated by a class must respect its methods and attributes in which the class has defined. Therefore, if you create (implicitly) a class that has the attribute id
, how could you have an object generated by this class without this attribute?
If you really want an object that contains only the attributes that suit you, you should encapsulate this result in another object defined by a new class (it could be a Struct
or OpenStruct
same). She would play the role of a DTO (Data Transfer Object).
2) If you want to return a standard hash, only with these fields:
Well, then you should make a loop and assemble your Hash
, there is no way, because the Rails
as quoted above, will always respect the contract defined by the class (implicitly). So even if you ask it to return as an object Hash
, it will be based on the attributes of your model.
My suggestion
You want to return an object of the type Hash
or another object you want to define (option 1), why you don’t create a method in your model that does this for you. The iteration to create a Hash or mount a new object (could be a Struct
) is very simple, and you wouldn’t expose this to the rest of the application. Something like:
class Employee < ActiveRecord::Base
def self.all_with_fields_that_i_want
all.map do |e|
OpenStruct.new({name: e.name, email: e.email})
end
end
end
results = Employee.all_with_fields_that_i_want
Hello Rafael, thank you for the clarification on the issue after so long. It has been so long since I posted who no longer remembered this question =D, anyway it is always good to have a very objective and thorough explanation about the problem. .
– Alessandro Sales
You’re welcome, and I’m glad you did! =)
– rafaels88