1

I am getting info from my database

@teams  = Team.select(:id,:name)

Then, I am rendering this info with an assosiation

render json: @teams, include: :players

This produce me the following input:

[
    {
    "id": 1,
    "name": "Lyon Gaming",
    "players": [
          {
            "name": "Jirall",
            "position": "Superior",
          },
          {
            "name": "Oddie",
            "position": "Jungla",
          }
      ]
}

]

How ever I need to sort the players in an specific order (not alphabetical)

I already have the sql statement to do it; how ever I dont know how to apply this method to each association.

I am looking something like:

render json: @teams, (include: :players, method: custom_order)

But this raise me an error.

Any ideas?

2 Answers 2

2

This should work:

render json: @teams, include: :players, methods: :custom_order

I'd like to add that if you will always want to return the object this way, you can add this to your model instead:

  def as_json(options = nil)
    super(include: :players, methods: :custom_order)
  end

As Adam has mentioned, active_model_serializers is good to have if your render json's start getting ugly. If the complexity doesn't grow too much, I always recommend keeping the dependencies down.

https://github.com/rails-api/active_model_serializers

Sign up to request clarification or add additional context in comments.

Comments

0

You need to read more about serializers in rails(This is good practice) Here you have a nice article about this https://www.sitepoint.com/active-model-serializers-rails-and-json-oh-my/

Then you can make something like this

app/serializers/team_serializer.rb

class TeamSerializer < ActiveModel::Serializer
  attributes :id, :name, :ordered_players
end 

app/controllers/teams_controller.rb

def index
  respond_with(Team.all.map(&TeamSerializer.method(:new)))
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.