对 json 响应控制器操作使用多个参数

Using multiple arguments for a json response controller action

在我的搜索控制器中,我使用 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

这就是您解决 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

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

# 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