RoR - Model.all, but without created_at and updated_at fields

Viewed 490

I am new to Ruby, so this question might look stupid for you, yeah. But still... I got a model Group, and when I run this

class GroupsController < ApplicationController
  prepend SimpleCommand
    ...
    def index
        @group = Group.all
        render json: @group
    end
    ...
    # some other stuff

...and then I get a response with array like this:

[
  {
    "id": 1020,
    "name": "НІ-16-1",
    "has_subgroups": true,
    "created_at": "2017-09-29T10:14:08.000Z",
    "updated_at": "2017-09-29T10:14:08.000Z"
  }
...
]

but I don't want to have those two last fields, so my answer is How to get rid of "created_at" and "updated_at" fields in a response?

UPD:

Found a great solution in original question I've accidentally made a duplicate for. Go ahead and read it

3 Answers

Every time you serve an object to the view as JSON Rails internally calls the function as_json. One way to get rid of those two fields is to override that function in your Group model:

 class Group < ActiveRecord::Base
      def as_json(options={})
        { id: id,
          name: name,
          has_subgroups: has_subgroups
        }
      end
  end

Or as @MrYoshiji suggested you could filter them out like so:

render json: @groups.to_json(except: [:created_at, :updated_at])

Rails come with jbuilder by default to generate the json response. You just have to find group/index.json.jbuilder and remove created_at and updated_at inside. And change your controller action to:

def index
    @group = Group.all
end

or if you need to support other formats:

def index
    @group = Group.all
    respond_to do |format|
      format.json
    end
end

You can see you don't have to specify anything as Rails will use your jbuilder file by default.

You could simply do:

class GroupsController < ApplicationController
  prepend SimpleCommand
    ...
  def index
     render json: Group.pluck(:id, :name, :has_subgroups)
  end
end

It may not matter to you, but I think this approach is faster because it doesn't instantiate all the Group objects.

Related