Ruby-on-rails 如何在 Rails 3 中使用 includes() 进行 find()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3943554/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:23:26  来源:igfitidea点击:

How to do find() with includes() in Rails 3

ruby-on-railsruby-on-rails-3

提问by 99miles

I'm trying to do something like this, but it's not working. How would I do this in Rails 3?

我正在尝试做这样的事情,但它不起作用。我将如何在 Rails 3 中做到这一点?

Student.find(12).includes(:teacher)

回答by Robert Speicher

You just have to be more careful with the order of the methods in this case:

在这种情况下,您只需要更加注意方法的顺序:

Student.includes(:teacher).find(12)

回答by mind.blank

Old question I know but just in case this helps someone...

我知道老问题,但以防万一这有助于某人...

Doing something like @student = Student.includes(:teacher).where(:id => 12)returns an array and so then using something such as @student.iddoesn't work.

做类似@student = Student.includes(:teacher).where(:id => 12)返回一个数组的事情,然后使用诸如此类的东西@student.id不起作用。

Instead you could do:

相反,你可以这样做:

@student = Student.includes(:teacher).where(:id => 12).first

Although Student.includes(:teacher).find(12)should work, but you can use the whereversion if you need to search by other/multiple fields.

虽然Student.includes(:teacher).find(12)应该可以工作,但是where如果您需要按其他/多个字段进行搜索,您可以使用该版本。

回答by Ivailo Bardarov

Student.includes(:teacher).where(:id => 12)

should work.

应该管用。

Can we see your models ?

我们可以看看你们的模型吗?

回答by coder_tim

You could try "where" instead of "find":

你可以试试“where”而不是“find”:

Student.includes(:teacher).where(:id => 12)

回答by Zelenka

There is no sense to use findwith includes. Eager loading helps us to load the associated records of the objects to prevent n+1 problem. With only one record you will never experience n+1 problem.

find与一起使用没有意义includes。Eager loading 帮助我们加载对象的关联记录,以防止 n+1 问题。只有一个记录,你永远不会遇到 n+1 问题。