【问题标题】:Rails Joins not working in SerializerRails Joins 在序列化器中不起作用
【发布时间】:2018-04-17 13:35:26
【问题描述】:

我对在 Rails 中构建 API 非常陌生,我目前处于需要使用当前活动记录序列化程序对象和我使用范围传递给它的另一个对象的情况。使用这些对象,我需要从序列化程序 def 运行 Join(Active Record Query Interface) 以找出特定数据。

虽然相同的查询在 Rails 控制台中运行良好,但尝试在序列化程序中执行它会引发“没有这样的方法错误”。

Section.joins(question_papers_sections: :questions).where('questions.id = object.id AND question_papers_sections.question_paper_id = current_exam_candidate.exam.question_paper.id')   

我可以在此处访问 Section 对象(尝试使用 binding.pry),序列化程序对象也可以访问,并且 current_exam_candidate 也可以访问。

【问题讨论】:

  • 如果需要,请询问模型结构等,希望根据我这可能不是必需的。另外,如果他们有另一种方法,请建议我,比如将对象值传递给辅助方法并在那里运行连接查询。请帮忙。

标签: ruby-on-rails serialization


【解决方案1】:

您可以在 API 的基本控制器中定义方法(如果有),或在相关模型中定义方法。你也应该稍微改变一下你的查询,我举个例子

示例:在您的控制器中

class Api::BaseController < ActionController::Base

  serialization_scope :view_context

  def find_question_section(object)
    section = Section.joins(question_papers_sections: :questions).where("questions.id = ? AND question_papers_sections.question_paper_id = ? ", object.id, current_exam_candidate.exam.question_paper.id).last
  end
end

在你的序列化器中

delegate :find_question_section , to: :scope 
find_question_section(object)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多