2014-03-27 25 views
1

我使用Gon gem將一些數據從Rails發送到BackBone。 我application_controller.rb應用程序佈局在render_to_string之後以純文本形式加載

class ApplicationController < ActionController::Base 
    before_action :init_gon 

    def init_gon 
    gon.me = render_to_string(template: 'users/_me.json.jbuilder') 
    end 
end 

所以在此之後,如果我打開我的web應用程序的任何頁面,它只顯示HTML爲純文本:

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" xmlns="" xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
..... 

我該如何處理呢?

回答

0

我認爲你的問題是你的渲染gon數據爲字符串。我認爲你應該通過你的數據,而不需要呈現字符串

我沒有任何特定部分的經驗,但我以前廣泛使用gon。這裏有一個RailsCast的覆蓋對象的片段:

只是剛創建腳本標籤,然後填滿了我們在控制器中設置的 數據坤變量。如果我們要定製返回給客戶端的JSON ,Gon支持RABL和 Jbuilder模板,這兩個模板已在最近的 劇集中進行了介紹。要定製所生產的產品列表中,我們 可以創建一個index.json.rabl文件返回的數據,並定義我們想要的屬性 並在那裏返回:

/app/views/products/index.json.rabl 
collection Product.limit(10) 
attributes :id, :name, :price 

/app/controllers/products_controller.rb 
class ProductsController < ApplicationController 
    def index 
    gon.rabl "app/views/products/index.json.rabl", as: "products" 
    end 
end 

的JBuilder

也許這會有幫助嗎?有一種方法來render GON data with jBuilder(因爲我看到你正在使用):

#app/controllers/application_controller.rb 
def init_gon 
    gon.jbuilder template: 'users/_me.json.jbuilder' 
end 

https://github.com/gazay/gon/wiki/Usage-with-jbuilder

+1

我只是用如你所說gon.jbuilder延伸,和所有的作品。非常感謝匹配! – kuatro