【问题标题】:How to add extra attributes to jbuilder index page如何向 jbuilder 索引页面添加额外的属性
【发布时间】:2014-11-13 19:45:18
【问题描述】:

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

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

  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 和总页数。

目前我拥有的是

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

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

【问题讨论】:

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


    【解决方案1】:

    经过漫长的忙碌,看看 jbuilder 显示模板是如何工作的,我意识到 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"}}]}
    

    【讨论】:

    • 感谢您发布您的答案,这对我有帮助。我认为你的两个方法是错误的。您应该使用json.total_pages @publishers.total_pagesjson.total_records @publishers.total_records
    • @publishers.total_records 很好,所以total_entries 也曾在 2014 年工作
    猜你喜欢
    • 1970-01-01
    • 2012-01-13
    • 2021-06-19
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    相关资源
    最近更新 更多