渴望加载多个关联和序列化

时间:2015-06-12 12:35:56

标签: ruby-on-rails-4 serialization eager-loading

在我的项目中,我有3个模型Assignment,Question和MultipleChoice,具有以下关联

assignment.rb

has_many :questions,  dependent: :destroy

question.rb

belongs_to :assignment, class_name: 'Assignment', foreign_key: :assignment_id
  has_many :multiple_choices, dependent: :destroy

multiple_choice.rb

belongs_to :question

现在我想进行如下查询

@assignment = Assignment.find(params[:id])
        @questions = @assignment.questions.includes(:multiple_choices)
This is not working as expected.

所以,我想要所有属于params [:id]的赋值的问题以及属于问题的相关多个选项。我上面的查询没有给出任何错误,但它只显示问题而不是与问题相关的多个选项。我怎样才能做到这一点?我正在学习rails的api开发。所以我想把这个值作为json发送,可能我需要序列化。我怎样才能做到这一点?我正在使用rails 4.

Edit

的输出
@questions = @assignment.questions.includes(:multiple_choices) and 
@questions = @assignment.questions.eager_load(:multiple_choices) and
@questions = @assignment.questions  are all same.

我不明白为什么输出不包含多个选择表中的任何值

输出命令

@assignment.questions.eager_load(:multiple_choices).to_sql id
    => "SELECT \"questions\".\"id\" AS t0_r0, \"questions\".\"content\" AS t0_r1, \"questions\".\"q_type\" AS t0_r2, \"quest
    ions\".\"created_at\" AS t0_r3, \"questions\".\"updated_at\" AS t0_r4, \"questions\".\"assignment_id\" AS t0_r5, \"multi
    ple_choices\".\"id\" AS t1_r0, \"multiple_choices\".\"content\" AS t1_r1, \"multiple_choices\".\"created_at\" AS t1_r2,
    \"multiple_choices\".\"updated_at\" AS t1_r3, \"multiple_choices\".\"question_id\" AS t1_r4 FROM \"questions\" LEFT OUTE
    R JOIN \"multiple_choices\" ON \"multiple_choices\".\"question_id\" = \"questions\".\"id\" WHERE \"questions\".\"assignm
    ent_id\" = $1"

2 个答案:

答案 0 :(得分:0)

Rails 4中includes函数的行为已更改。您可以在此处找到更多详细信息:

http://blog.arkency.com/2013/12/rails4-preloading/

我还想,如果您使用eager_load代替includes,您将获得所需的结果。

答案 1 :(得分:0)

@assignment是一个从中获取问题的对象。

但是使用@questions = @ assignment.questions.includes(:multiple_choices)如何在不调用对象的情况下获取multiple_choices?

试试这个 - >

@assignment = Assignment.includes(:questions).find(params [:id]) @ assignment.questions.includes(:multiple_choices).collect {| question | question.multiple_choices}

这还包括急切加载。

希望你能得到你所期望的。