如何向jbuilder索引页面添加额外的属性

时间:2014-09-19 08:58:04

标签: ruby-on-rails json ruby-on-rails-4 jbuilder

我一直在尝试将自定义属性添加到jbuilder,就像我在显示页面中一样添加到我的索引页面,用于分页将paginate并且不显示自定义属性。

例如我在控制器操作中的内容是

  def index
    #respond_with
    @publishers = Publisher.paginate(:page => params[:page], :per_page => 30)
    respond_to do |format|
      format.json
    end
  end

我的index.json.jbuilder是

json.array!(@publishers) do |publisher|
  json.extract! publisher, :id, :name, :url
  json.categories do
    publisher.categories.each do |category|
      json.name category.name
      json.id category.id
      json.url url_for(category)
    end
  end
end

我想拥有的是

json.current_page @publishers.current_page
json.total_pages @publishers.totla_entries

json.array!(@publishers) do |publisher|
  json.extract! publisher, :id, :name, :url
  json.categories do
    publisher.categories.each do |category|
      json.name category.name
      json.id category.id
      json.url url_for(category)
    end
  end
end

这样我就可以在索引页的json输出中显示current_page和total pages。

目前我所拥有的是

[{"id":1,"name":"facebook","url":"http://www.facebook.com","categories":{"name":"Art and Crafts","id":1,"url":"/categories/1-art-and-crafts"}}]

我怎样才能做到这一点。我也在使用willpaginate

1 个答案:

答案 0 :(得分:8)

经过漫长的喧嚣,看看jbuilder如何展示模板的工作方式,我意识到了json.array!方法覆盖了块之外的任何东西所以我做了几个tweek并通过在下面的根节点中敲击来解决它

json.current_page @publishers.current_page
json.total_pages @publishers.total_entries
json.total_records Publisher.count

json.publishers do |publishersElement|
  publishersElement.array!(@publishers) do |publisher|
    json.extract! publisher, :id, :name, :url
    json.categories do
      publisher.categories.each do |category|
        json.name category.name
        json.id category.id
        json.url url_for(category)
      end
    end
  end
end

我得到的输出就是这个

{"current_page":1,"total_pages":1,"total_records":1,"publishers":[{"id":1,"name":"Bellanaija","url":"http://www.bellanaija.com","categories":{"name":"Art and Crafts","id":1,"url":"/categories/1-art-and-crafts"}}]}