我一直在尝试向jbuilder添加自定义属性,就像我在显示页中向索引页进行分页一样,它将分页并且其不显示自定义属性。

例如我在 Controller 操作中拥有的是

  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页面。

目前我所拥有的是
[{"id":1,"name":"facebook","url":"http://www.facebook.com","categories":{"name":"Art and Crafts","id":1,"url":"/categories/1-art-and-crafts"}}]

我怎么能做到这一点。我也在用willpaginate

最佳答案

经过长时间的忙碌,看看jbuilder show模板是如何工作的,我意识到json.array!方法覆盖了块外的所有内容,所以我做了几个星期,并通过将其拍成如下所示的根节点来解决了该问题

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"}}]}

关于ruby-on-rails - 如何向jbuilder索引页面添加额外的属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25930100/

10-10 00:32