0

在我的搜索控制器中,我使用 json 渲染调用进行站点搜索。我现在需要将自定义实例方法传递给 JS 文件。问题是,当我尝试用逗号分隔必要的方法 ( to_json) 时,我在控制台中收到此错误:

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

控制器代码

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

型号代码

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

1 回答 1

1

这就是解决 ActiveModelSerializer 问题的方法。

# 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

如果您想为游戏的搜索结果表示与普通表示使用不同的序列化程序,您可以指定序列化程序:

# 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
于 2015-12-01T14:22:00.897 回答