【问题标题】:Rails ActiveRecord relation to JSONRails ActiveRecord 与 JSON 的关系
【发布时间】:2013-10-10 00:44:34
【问题描述】:

我正在使用 Rails 查询数据并将其放入哈希中......

class AssignmentsController < ApplicationController
  respond_to :json

  def index
    student = Student.find(current_user.student_id)
    @assignments = Hash.new
    @assignments["individual"] = Assignment.where(:student_id => student.id)

    unless student.group_lesson_ids.nil?
      student.group_lesson_ids.each do |g|
        group_lesson = GroupLesson.find(g)
        @assignments[group_lesson.name] = Assignment.where(:group_lesson_id => g)
      end
    end
  end

end

然后我希望 Rabl 将其转换为 JSON 以供 Marionette 应用程序使用。

这是 Rabl 文件

object @assignments
attributes :id, :title, :student_id, :assigned

但是当我在浏览器中检查 JSON 时,它只会显示 ActiveRecord 关系。

{

    "#<ActiveRecord::Relation::ActiveRecord_Relation_Assignment:0x007fa2956b43a8>": [
        { },
        { },
        { }
    ]

}

我知道这是因为延迟加载的概念,但是在这种情况下我应该怎么做才能让 Marionette 可以使用 JSON?

【问题讨论】:

  • 你的 RABL 模板是什么?另请注意,您可以在关系上使用 to_a 加载记录。
  • 在原始问题中添加了模板。感谢您对 to_a 的提醒

标签: ruby-on-rails json marionette rabl


【解决方案1】:

如果你有指定模型之间的关系,这个怎么样(因为我目前没有使用 RABL,所以没有测试):

class AssignmentsController < ApplicationController
  respond_to :json

  def index
    @student = current_user.student
  end
end

RABL 模板:

object false

node :assignments do
  child @student.assignments => :individual

  @student.group_lessons.each do |gl|
    node(gl.name) { gl.assignments }
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多