【问题标题】:Prawn error "data must be a two dimensional array of cellable objects"大虾错误“数据必须是可单元格对象的二维数组”
【发布时间】:2013-06-10 09:42:46
【问题描述】:

我正在使用 Prawn 生成 PDF 文档,但在尝试为项目生成表格时出现上述错误。有什么想法可以解决这个问题吗?

app/models/storage_request.rb

class StorageRequest < ActiveRecord::Base
  has_many :packages

  accepts_nested_attributes_for :packages, :allow_destroy => true
  attr_accessible :user_id, :state, :packages_attributes
end

app/models/package.rb

class Package < ActiveRecord::Base
  belongs_to :storage_request
  has_many :items

  accepts_nested_attributes_for :items, allow_destroy: true
  attr_accessible :user_id, :state, :items_attributes
end

app/models/item.rb

class Item < ActiveRecord::Base
  belongs_to :package

  attr_accessible :name, :user_id
end

app/pdfs/storage_request_pdf.rb

class StorageRequestPdf < Prawn::Document
  def initialize(storage_request, view)
    super(top_margin: 50)
    @storage_request = storage_request
    @view = view
    list_items
  end

  def list_items
    move_down 20
    text "Summary", size: 30, style: :bold, align: :center

    table item_rows do
      row(0).font_style = :bold
      self.row_colors = ["DDDDDD", "FFFFFF"]
      self.header = true
    end
  end

  def item_rows
    @storage_request.packages.map do |package|
      package.items.map do |item|
        ([["ID", "Item Name"]] +
        [item.id, item.name])
      end
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails prawn


    【解决方案1】:

    您的 item_rows 方法返回一个格式错误的数组。它将标题添加到每一行并返回一个数组,如下所示:

    [ [["ID", "Item Name"], 1, "Foo"],
      [["ID", "Item Name"], 2, "Bar"],
      [["ID", "Item Name"], 3, "Baz"] ]
    

    而 Prawn 需要这样的数组:

    [ ["ID", "Item Name"],
      [1, "Foo"],
      [2, "Bar"],
      [3, "Baz"] ]
    

    您应该始终为您的代码编写测试以尽早发现此类错误。

    我会在不同的方法中定义行和标题:

    def item_header
      ["ID", "Item Name"]
    end
    
    def item_rows
      @storage_request.packages.map do |package|
        package.items.map { |item| [item.id, item.name] }
      end
    end
    
    def item_table_data
      [item_header, *item_rows] 
    end
    

    并使用以下命令创建表:

    table(item_table_data) do
      # ...
    end
    

    item_rows 方法仍然有点难看,因为它深入到对象中。我会在StorageRequest 中添加一个has_many :through association

    class StorageRequest < ActiveRecord::Base
      has_many :packages
      has_many :items, :through => :packages
    

    并重构item_rows 方法:

    def item_rows
      @storage_request.items { |item| [item.id, item.name] }
    end
    

    【讨论】:

    • 谢谢。让我测试一下并恢复结果。
    • 有没有办法将表格数组放到调试器中,这样我就可以看到数组的格式了?
    • @ctilley79 当然,您可以使用Pry 或使用Awesome Print 将数组打印到控制台。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2016-05-21
    • 1970-01-01
    • 1970-01-01
    • 2020-11-14
    • 2014-06-04
    相关资源
    最近更新 更多