1

我有一个提交模型

belongs_to :report
has_many :answers

报告模型

has_many :questions

问题模型

has_many :answers   # answer has submission_id

现在在 rabl 模板中我需要这样的输出

        object @submission
        attributes :status, :submission_time

        child :report do
            attribute :id, :name
            child :questions do
                attribute :id, :content
                node(:answers_count) do |question|
                    question.answers.where("submission_id = ?", @submission.id).count
                end
                node(:answers) do |question|
                    question.answers.where("submission_id = ?", @submission.id).collect{ |answer| {:name => answer.name, :id => answer.id}}
                end
            end
        end

这工作得很好,但问题出在我正在使用@submission 的 answers_count 和答案节点中,因为索引操作不起作用。

它在显示操作中很好,但索引操作正在创建问题,因为@submission 在索引操作中不可用。

PS:一旦我解决了这个问题,我会将大查询从视图移动到模型。我知道,为了简单起见,我已经粘贴了该内联。

4

2 回答 2

2

这不是最好的解决方案,但它会起作用

object @submission
attributes :status, :submission_time

child :report do
    attribute :id, :name

    submission_id = locals['submission'] ? locals['submission'].id : locals[:object].id

    child :questions do
        attribute :id, :content
        node(:answers_count) do |question|
            question.answers.where("submission_id = ?", submission_id ).count
        end
        node(:answers) do |question|
            question.answers.where("submission_id = ?", submission_id ).collect{ |answer| {:name => answer.name, :id => answer.id}}
        end

    end
end
于 2013-05-21T06:28:51.647 回答
0

这应该对您有用,尽管不可否认,这有点麻烦。我为后代保留了下面的非工作解决方案:

object @submission
attributes :status, :submission_time

child :report do
    submission_id = root_object.id
    attribute :id, :name
    child :questions do
        attribute :id, :content
        node(:answers_count) do |question|
            question.answers.where("submission_id = ?", submission_id).count
        end
        node(:answers) do |question|
            question.answers.where("submission_id = ?", submission_id).collect{ |answer| {:name => answer.name, :id => answer.id}}
        end
    end
end    

不正确的解决方案:

用于root_object此:

node(:answers_count) do |question|
  question.answers.where("submission_id = ?", root_object.id).count
end

或者,将其作为参数传递给child :report块:

    object @submission
    attributes :status, :submission_time

    child :report do |submission|
        attribute :id, :name
        child :questions do
            attribute :id, :content
            node(:answers_count) do |question|
                question.answers.where("submission_id = ?", submission.id).count
            end
            node(:answers) do |question|
                question.answers.where("submission_id = ?", submission.id).collect{ |answer| {:name => answer.name, :id => answer.id}}
            end
        end
    end

不幸的是,这些方法都不起作用。第一个解决方案不起作用,因为root_object块范围发生了变化(它标识了包含块的父级)。第二种解决方案不起作用,因为与node,不同child的是,为该迭代传入了子对象。不幸的是,这与文档让您相信的相反。

于 2013-05-20T13:51:40.723 回答