2011-03-12 50 views
1

在HTML預覽我們使用Mustache模板,我想使我們的回報率的Web應用程序的預覽視圖,結合了模板,我們已經儲存在我們的數據庫中的一些數據,但它沒有像我預期的那樣工作,並且在互聯網上搜索(包括SO!)後,我沒有發現任何包含活動模型的示例。如何使用Ruby on Rails的鬍子從加載ActiveModel

你怎麼管加載ActiveModel記錄小鬍子與模板合併?

的設置:

的架構

create_table "templates", :force => true do |t| 
    t.string "kind" 
    t.text  "data" 
    t.integer "data_count" 
end 
create_table "bars", :force => true do |t| 
    t.string "guid" 
    t.string "name" 
    t.string "summary" 
end 

沒有什麼特別之處的車型。無論是從子類的ActiveRecord :: Base的

class Bars < ActiveRecord::Base 
end 
class Templates < ActiveRecord::Base 
end 

的控制器

class TemplateController < ApplicationController 
    def preview 
    @result = Mustache.render(template.data, :bars => Bar.limit(template.data_count)).html_safe 
    end 
end 

<%= @result %> 

的路線

get 'templates/:id/preview' => 'templates#preview', :as => 'templates_preview' 

數據

y Bar.all 

--- 
- !ruby/object:Bar 
    attributes: 
    guid: "1" 
    name: "test1" 
- !ruby/object:Bar 
    attributes: 
    guid: "2" 
    name: "test2" 

模板(我已經簡化,例如目的HTML)

<html> 
<head> 
</head> 
<body> 
    {{#bars}} 
    <a href="{{guid}}">{{name}}</a> 
    {{/bars}} 
</body> 
</html> 

結果

<html> 
<head> 
</head> 
<body> 
    <a href=""></a> 
</body> 
</html> 

的期望

<html> 
<head> 
</head> 
<body> 
    <a href="1">test1</a><a href="2">test2</a> 
</body> 
</html> 

我希望有一個簡單的回答這個,我只是想念它。謝謝。

回答

6

請問,如果你改變你的控制器到它的工作:

@result = Mustache.render(template.data, :bars => Bar.limit(template.data_count).all).html_safe 

(加Bar.limit(template.data_count).all通話)

我是很新,小鬍子,但glancing very quickly through the code似乎表明,它調用這對於節:

v = [v] unless v.is_a?(Array) || defined?(Enumerator) && v.is_a?(Enumerator) 

Bar.limit(template.data_count)返回ActiveRecord::Relation,既不一個Array也不是Enumerator。上的關係主叫.all把它變成一個數組並導致鬍鬚到它相應地通入部分。

+0

你,先生,是輝煌的。謝謝。這實際上是問題所在。 – sorens 2011-03-12 17:35:27

+0

很高興幫助!^_ ^ – 2011-03-12 17:36:03