如何访问prawn表格单元格中的内容的另一个模型/记录?

时间:2018-03-29 10:44:34

标签: ruby-on-rails

我正在使用表格(Prawn& Prawn-Table)构建PDF,其中某个章节的所有教育目标(EO)都与其用例(UC)一起显示。我直接得到EO,但不知道如何让UC进入细胞。 这是我的代码。也许有人有想法或知道如何做得比我好。 提前谢谢!

class UseCase < ApplicationRecord
    has_and_belongs_to_many :educational_objectives
end

class EducationalObjective < ApplicationRecord
    has_and_belongs_to_many :use_cases
end

应用程序/ PDF文件/ chapter_pdf.rb

require 'prawn'

class ChapterPdf < Prawn::Document
    def initialize(eo, chapter)
        @educational_objectives = eo
        @chapter = chapter
        @subject_id = @chapter.subject_id

        chapter_header
        chapter_text
        items
    end

    ...

    def items
        table_data = []

        @educational_objectives.map do |item|
            table_data << [item.position, item.educational_objective, use_cases(item.id)]
        end
        ...
    end

    def use_cases(id)
      ucs = @educational_objectives.joins(:use_cases).
                                where(educational_objectives: {id: id}).
                                select(:use_case)
      ucs.join do |uc|
        uc
      end
    end
end

当我查看服务器日志时,我看到了:

SELECT "use_case" FROM "educational_objectives" INNER JOIN "educational_objectives_use_cases" ON "educational_objectives_use_cases"."educational_objective_id" = "educational_objectives"."id" INNER JOIN "use_cases" ON "use_cases"."id" = "educational_objectives_use_cases"."use_case_id" WHERE "educational_objectives"."chapter_id" = ? AND "educational_objectives"."id" = ?  [["chapter_id", 9], ["id", 169]]

SELECT  1 AS one FROM "educational_objectives" INNER JOIN "educational_objectives_use_cases" ON "educational_objectives_use_cases"."educational_objective_id" = "educational_objectives"."id" INNER JOIN "use_cases" ON "use_cases"."id" = "educational_objectives_use_cases"."use_case_id" WHERE "educational_objectives"."chapter_id" = ? AND "educational_objectives"."id" = ? LIMIT ?  [["chapter_id", 9], ["id", 171], ["LIMIT", 1]]

在我的PDF中,我在单元格中看到

#<EducationalObjective:0x00007f8569997370>#<EducationalObjecti
ve:0x00007f85699971e0>#<EducationalObjective:0x00007f85699970
50>

我的错误在哪里?然后我想用逗号分隔显示它... 是的,我是新手,非常感谢你的帮助!

1 个答案:

答案 0 :(得分:0)

has_and_belongs_to_many关联提供a number of helper methods - 对于您的情况,您可以致电educational_objective.use_cases以返回相关记录的集合。

这意味着您可以删除use_cases方法并使用以下内容:

  table_data = @educational_objectives.map do |item|
    [item.position, item.educational_objective, item.use_cases]
  end

当您使用map时,无需使用此外定义的数组。

这假设上面示例中的itemEducationalObjective的一个实例,虽然我对此感到有些困惑,因为您还要调用item.educational_objective

如果有任何问题可以解决,或者您有任何问题,请告诉我。