我有一个提交模型
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
这工作得很好,但问题出在answers_count和答案节点我正在使用@submission,因为该索引操作不起作用。
它在show动作中很好,但索引动作正在创建问题,因为@submission在索引操作中不可用。
PS:一旦我解决了这个问题,我会将大查询从视图移动到模型。我知道,为了简单起见,我已粘贴内联。
答案 0 :(得分: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
答案 1 :(得分: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
传递了该迭代的子对象。不幸的是,这与你认为的the documentation相反。