0

I'm working on exposing an API using RABL. Exposing the views is easy enough, but I've run into trouble having my own application consume those views.

For example, assume I have an endpoint at http://example.com/api/articles, which produces a JSON representation of the articles.

In my ArticlesController#index action, I wish to render a (HAML) view that shows a list of the articles. Rather than duplicate the logic from ArticlesApiController#index, I want to simply use that data—i.e., I want to say "go get this data from the /articles API endpoint," and then pass that data to the HAML view.

How can I do that? Or, is this the wrong way to go about doing this?

4

1 回答 1

1

在 RABL 上观看此截屏视频。

在您看来,您可以按如下方式添加来自 RABL 的数据(取自 railscast 示例):

<div id="articles" 
   data-articles="<%= render(template: "articles/index.json.rabl") %>">

笔记

您可以使用gon gem使数据访问更加简单。

在您的控制器中

def index
  @articles = Article.all 

  # initialize the JS variable upon HTML request
  gon.rabl if request.format == Mime::HTML

end

现在您可以访问 javascript 中的数据,如下所示:

alert(gon.articles)
于 2012-06-19T23:51:03.207 回答