When I want to remove these datas from one resource I do:
@teams = Team.all
render json: @teams, :except => [:created_at, :updated_at],
My doubt is when I have many includes like these:
@teams = Team.all
render json: @teams, :include => [:stadiums, :scores, :links, :rounds]
How do I remove from all of them?
Correction: You can do something like
There is no simple way of doing this without iterating over the relevant models, obtaining the attributes hash and selecting the desired attributes.Such use cases are often solved elegantly using json templating DSLs like jbuilder or rabl.
To illustrate this using jbuilder:
Which would produce the output as:
If you find this too verbose for your use case, as @liamneesonsarmsauce has pointed out in the comments another solution is to use ActiveModel Serializers
Using this approach you can specify a serializer class for each of your models, listing the allowed attributes which would become a part of json response. For example
You can define similar serializers for associated models as well.
Since associations are seamlessly handled in a way that is already familiar to rails developers, unless you require much customization of the generated json response, this is a more succinct approach.
How 'bout adding to
models/application_record.rb
then use it like
So in your case, your code remains the same
and yeah, you get them all without
:created_at
and:updated_at
. No need to tell rails to exclude that in every single model, hence keeping the code real DRY.