ruby-on-rails – Select without the id (RoR) field


I have a very silly question, I'm making a little system with Ruby on Rails and I need to make a select where the id field doesn't come, the problem is that this field is always present, for example:'nome, email').all

The code above should return several records and bring only the name and email fields as I'm configuring, as with other fields, but the id is nil, but it doesn't disappear, the record looks like this:

  id: null,
  email: "Executiva de Atendimento"

How do I remove this field objectively, as I know I could iterate over the result and create a simple list, but I believe rails supports solving this without major maneuvers.

I hope I was clear and I look forward to a little help, vlw.


Alessandro, this question of yours is complicated and requires us to understand a few things:

1) If you want to return an object without the id attribute, Rails won't do that, and I'll explain why:

You have created a class, the ActiveRecord model that is implicitly linked to the database 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 linked. And we know that every object generated by a class must respect its methods and attributes that 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 in another object defined by a new class (it could be a Struct or OpenStruct anyway). It would play the role of a DTO (Data Transfer Object) .

2) If you want to return a default hash, only with these fields:

Well, then you must do a loop and assemble your Hash , there's no way, because Rails as mentioned above, will always respect the contract defined by the class (implicitly). So even if you ask it to return as a Hash object, it will be based on your model attributes.

My sugestion

If you want to return an object of type Hash or another object that you want to define (option 1), why don't you create a method in your model that does that for you. The iteration to create a Hash or assemble 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 do |e|{name:, email:})

results = Employee.all_with_fields_that_i_want
Scroll to Top