【问题标题】:Using multiple arguments for a json response controller action对 json 响应控制器操作使用多个参数
【发布时间】:2015-12-01 13:32:19
【问题描述】:

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

【问题讨论】:

  • 使用 ActiveModel 序列化器或 jBuilder。在控制器中创建复杂的 JSON 响应并不是一个好主意。
  • 如何将 jbuilder 文件与我需要使用的 javascript 互连?
  • 您将使用 ajax 从 javascript 中获取 JSON 格式的搜索数据。 jBuilder 的工作方式有点像视图 - 除了它生成 JSON 或 XML 而不是 HTML。
  • 根据您的推荐,我刚刚检查了 ActiveModel Serializers Railscast,它看起来绝对值得一试。感谢您为我指明正确的方向!如有需要会更新。
  • 但是您的错误有点令人困惑。我最好的猜测是您使用的是旧版本的 ruby​​,它不支持 1.9 哈希样式 { foo: :bar },这就是它期待 hashrocket (=&gt;) 的原因。您可以使用ruby -v 对其进行测试。如果是这样,您应该尽快升级您的 ruby​​,因为它已经 EOL 很长时间并且不安全。

标签: ruby-on-rails ruby json controller respond-to


【解决方案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-03-11
    • 1970-01-01
    • 2016-11-13
    • 2016-02-23
    • 1970-01-01
    • 2010-11-27
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多