Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/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
Ruby on rails 有没有办法避免这种可能不必要的查询?_Ruby On Rails - Fatal编程技术网

Ruby on rails 有没有办法避免这种可能不必要的查询?

Ruby on rails 有没有办法避免这种可能不必要的查询?,ruby-on-rails,Ruby On Rails,因此,我的控制器中有以下几行: if Account.includes(:student).where(:email => account[:email]).any? student=Account.find_by_email(account[:email]).student @stream.students << student else #... end if账户。包括(:学生)。其中(:email=>账户

因此,我的控制器中有以下几行:

 if Account.includes(:student).where(:email => account[:email]).any?
      student=Account.find_by_email(account[:email]).student
      @stream.students << student
      else
        #...
      end
if账户。包括(:学生)。其中(:email=>账户[:email])。有吗?
学生=帐户。通过电子邮件查找(帐户[:电子邮件])。学生
@stream.students改为:

student = Account.includes(:student).where(:email => account[:email]).first
if student
# code

first
返回第一条记录或nil,如果nil将使if语句失败

我认为以下代码将使其成为:

student_account = Account.includes(:student).where(:email => account[:email]).first
if !student_account.nil?
  student=student_account.student
  @stream.students << student
else
    #...
end
student\u account=account。包括(:student)。其中(:email=>account[:email])。首先
如果!学生账户。零?
学生=学生账户

@stream.students我想我应该重组为:

if student = Student.joins(:accounts).
                     where(:accounts => {:email => account[:email]}).
                     take
  @stream.students << student
  else
    #...
  end
如果student=student.join(:accounts)。
其中(:accounts=>{:email=>account[:email]})。
拿

@stream.students我用记忆在iPad上打字,但我认为你可以做如下事情:

if student = Student.joins(:account).find_by(accounts: { email: account[:email] })
  ...
end

这不是将学生创建为Account的实例吗?是的,上面的答案是正确的,我一开始读错了问题。这返回一个关系,而不是一个单独的学生对象,正如所描述的,我想需要调整。