Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby-on-rails-4/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Activerecord Rails:通过进行额外的sql查询来查找_,以前做过包含_Activerecord_Ruby On Rails 4 - Fatal编程技术网

Activerecord Rails:通过进行额外的sql查询来查找_,以前做过包含

Activerecord Rails:通过进行额外的sql查询来查找_,以前做过包含,activerecord,ruby-on-rails-4,Activerecord,Ruby On Rails 4,我有三门课: class Batch has_many :final_grade_batches end class FinalGradeBatch belongs_to :batch belongs_to :student end class Student has_many :final_grade_batches end 我想通过以下方式检索final\u grade\u批次: batch = Batch.includes(:final_grade_batches).

我有三门课:

class Batch
  has_many :final_grade_batches
end

class FinalGradeBatch
  belongs_to :batch
  belongs_to :student
end

class Student
  has_many :final_grade_batches
end
我想通过以下方式检索
final\u grade\u批次

batch = Batch.includes(:final_grade_batches).find(1)
batch.final_grade_batches.find_by(student_id: 2)
最后一行生成此SQL查询:

FinalGradeBatch Load (0.6ms)  SELECT "final_grade_batches".* FROM "final_grade_batches" WHERE "final_grade_batches"."batch_id" = $1 AND "final_grade_batches"."student_id" = 2 LIMIT 1  [["batch_id", 1]]
如果我在
Batch
find
查询中包含
final\u grade\u批次
,为什么它要再次查找
final grade批次
?我知道它需要找到一个具有学生id的,但是Rails是否应该进行查询以获得该id?现在不是已经载入内存了吗


我有没有办法在Rails不再次访问数据库的情况下获得一个
最终成绩批次
?谢谢

find_by
总是进行数据库查询。将其替换为:

batch.final_grade_batches.select( |grade_batch| grade_batch.student_id == 2).first
这适用于已从数据库加载的数组,而不是执行其他查询