Alessandro, this is a complicated question and requires us to understand some things:
1) If you want to return an object without the id
attribute, Rails will not do this, and I'll explain why:
You have created a class, the ActiveRecord
model that is implicitly bound to the bank records. As in Rails everything is by convention, it admits that its class declares the attributes referring to the fields of 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. So, if you create (implicitly) a class that has the id
attribute, 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 into another object defined by a new class (it could be a Struct
or OpenStruct
itself). It would act as a DTO (Data Transfer Object) .
2) If you want to return a default hash, only with these fields:
Well, there you should loop and mount your
Hash
, there is no way, because
Rails
as quoted above, will always respect the contract defined by the class (implicitly). So even if you ask for it to return as a
Hash
object, it will be based on the attributes of your model.
My suggestion
If you want to return an object of type Hash
or another object that you want to set (option 1), why do not you create a method in your model that does this for you. The iteration to create a hash or mount a new object (could be Struct
) is very simple, and you would not expose it 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