Rails 4 - remove "created_at" and "updated_at" from rendering

When I want to delete this data from one resource, I:

@teams = Team.all

render json: @teams, :except => [:created_at, :updated_at],

My doubt is that I have many of these:

@teams = Team.all

render json: @teams, :include => [:stadiums, :scores, :links, :rounds]

How to remove all of them?

+4
source share
2 answers

Correction: You can do something like

render json: @teams.to_json(:except => [:created_at, :updated_at], :include => { :stadiums => { :except => [:created_at, :updated_at]}, ... })

There is no easy way to do this without iterating over the appropriate models, obtaining attribute hashes, and selecting the desired attributes.

Such use cases are often resolved elegantly using json templating DSLs such as jbuilder or rabl .

To illustrate this with jbuilder:

Jbuilder.encode do |json|
  json.array! @teams do |team|
    json.name team.name
    json.stadiums team.stadiums do |stadium|
      json.name stadium.name
      # Other relevant attributes from stadium
    end
    # Likewise for scores, links, rounds
  end
end

Which would give an output like:

[{
  name: "someteamname",
  stadiums: {
    name: "stadiumname"
  },
  ...
}, {...},...]

, @liamneesonsarmsauce, - ActiveModel

, serializer , , json-.

class TeamSerializer  < ActiveModel::Serializer
  attributes :id, :name # Whitelisted attributes

  has_many :stadiums
  has_many :scores
  has_many :links
  has_many :rounds
end

.

, rails, json, .

+6

models/application_record.rb

# Ignore created_at and updated_at by default in JSONs 
# and when needed add them to :include
def serializable_hash(options={})
  options[:except] ||= []
  options[:except] << :created_at unless (options[:include] == :created_at) || (options[:include].kind_of?(Array) && (options[:include].include? :created_at))
  options[:except] << :updated_at unless (options[:include] == :updated_at) || (options[:include].kind_of?(Array) && (options[:include].include? :updated_at))

  options.delete(:include) if options[:include] == :created_at
  options.delete(:include) if options[:include] == :updated_at
  options[:include] -= [:created_at, :updated_at] if options[:include].kind_of?(Array)

  super(options)
end

,

render json: @user
# all except timestamps :created_at and :updated_at

render json: @user, include: :created_at
# all except :updated_at

render json: @user, include: [:created_at, :updated_at]
# all attribs

render json: @user, only: [:id, :created_at]
# as mentioned

render json: @user, include: :posts
# hurray, no :created_at and :updated_at in users and in posts inside users

render json: @user, include: { posts: { include: :created_at }}
# only posts have created_at timestamp

,

@teams = Team.all
render json: @teams, :include => [:stadiums, :scores, :links, :rounds]

, :created_at :updated_at. , , , DRY.

+1

All Articles