使用Prawn创建包含属于collectionproxy的值数组的PDF
Ruby on Rails 4
创建带有问题和答案的PDF。 问题很好。 现在我试图将相关答案放在每个问题的旁边或下面。
我能够在每个问题上显示一个答案,现在我遇到了问题,因为答案存储在数组中。
控制器:
def show @all_answers = [] @test = Test.find(params[:id]) @test_questions = @test.questions @test_questions.each do |a| @all_answers << Answer.find_all_by_question_id(a) end respond_to do |format| format.html format.pdf do pdf = TestReport.new(@test_questions, @all_answers) send_data pdf.render, filename: 'certification_test.pdf', type: 'application/pdf' , disposition: 'inline' end end end
PDF类代码:
class TestReport < LayoutPdf def initialize(test=[], answer=[]) super() @test_questions = test @all_answers = answer header 'Certification Test' display_test footer end def display_test table test_questions do self.header = true self.column_widths = [40, 300, 200] end end def test_questions [['#', 'Question']] + @test_me ||= @test_questions.map { |e| [e.id, e.content] } + #@all_answers.each do |a| a.content end @answer_me ||= @all_answers.map { |a| [a.content] } end end
@all_answers是这样的数组:
[[#, #, #], [#, #]]
我为这一行得到的错误: @answer_me ||= @all_answers.map { |a| a.content }
@answer_me ||= @all_answers.map { |a| a.content }
undefined method `content' for #
@all_answers
是一个数组数组。 你应该在迭代之前弄平它:
@answer_me ||= @all_answers.flatten.map { |a| a.content }