ruby-on-railsrubyjsoncontrollerrespond-to

Using multiple arguments for a json response controller action


In my search controller I'm using a json render call for site search. I now need to pass a custom instance method to a JS file. The problem is, when I try to comma separate the necessary method (to_json) I'm getting this error in my console:

SyntaxError (/game_app/app/controllers/search_controller.rb:13: syntax error, unexpected '}', expecting =>):
  app/controllers/search_controller.rb:13: syntax error, unexpected '}', expecting =>

Controller Code

def autocomplete
  render json: Game.search(params[:query], fields: [{ title: :word_start }], limit: 10), Game.to_json(methods: [:box_art_url])
end

Model Code

class Game < ActiveRecord::Base
  def box_art_url
    box_art.url(:thumb)
  end
end

Solution

  • This is how you would solve the problem with ActiveModelSerializers.

    # Gemfile
    # ...
    gem 'active_model_serializers'
    

    # app/controllers/games_controller.rb
    # ...
    def autocomplete
      @games = Game.search(params[:query], fields: [{ title: :word_start }], limit: 10)
      render json: @games
    end
    

    # app/serializers/game_serializer.rb
    class GameSerializer < ActiveModel::Serializer
      attributes :title, :box_art_url
    end
    

    In case you want to use a different serializer for the search results representation of games vs the normal representation you can specify the serializer:

    # app/controllers/games_controller.rb
    # ...
    def autocomplete
      @games = Game.search(params[:query], fields: [{ title: :word_start }], limit: 10)
      render json: @games, each_serializer: GameSearchResultSerializer
    end