0

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
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
  • Use ActiveModel Serializers or jBuilder. Creating complex JSON responses in your controllers is rarely a good idea. – max Dec 01 '15 at 13:52
  • How would I go about in interconnecting the jbuilder file with the javascript I need to use? – Carl Edwards Dec 01 '15 at 13:54
  • You would use ajax to fetch the search data as JSON from javascript. jBuilder works kind of like a view - except that it produces JSON or XML instead of HTML. – max Dec 01 '15 at 13:57
  • From your recommendation I just checked out the ActiveModel Serializers Railscast and it definitely looks like its worth trying. Thanks for pointing me in the right direction! Will update if need-be. – Carl Edwards Dec 01 '15 at 14:05
  • But your error is bit perplexing. My best guess is that you are using a old version of ruby which does not support the 1.9 hash style `{ foo: :bar }` which is why it is expecting a hashrocket (`=>`). You can test it with `ruby -v`. If so you should upgrade your ruby asap as it has been EOL a long time and is unsecure. – max Dec 01 '15 at 14:09
  • Don't think that's the case here. Using: `ruby 2.0.0p481` – Carl Edwards Dec 01 '15 at 14:13

1 Answers1

1

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
max
  • 96,212
  • 14
  • 104
  • 165