2015-12-01 29 views
0

在我的搜索控制器中,我使用json渲染調用進行站點搜索。我現在需要將自定義實例方法傳遞給JS文件。問題是,當我嘗試逗號分隔的必要方法(to_json)我得到這個錯誤在我的控制檯:對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 
+0

使用ActiveModel序列化器或jBuilder。在您的控制器中創建複雜的JSON響應幾乎不是一個好主意。 – max

+0

我該如何去將jbuilder文件與我需要使用的javascript相互關聯? –

+0

您將使用ajax從javascript獲取搜索數據作爲JSON。 jBuilder的工作類似於一個視圖 - 除了它生成JSON或XML而不是HTML。 – max

回答

1

這就是你將如何解決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 

如果你要使用的遊戲VS正常表示搜索結果表示不同的序列化,你可以指定串行:

# 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