如何在Rails 3中使用includes()执行find()

99m*_*les 42 ruby-on-rails ruby-on-rails-3

我正在尝试这样做,但它不起作用.我如何在Rails 3中执行此操作?

Student.find(12).includes(:teacher)
Run Code Online (Sandbox Code Playgroud)

Rob*_*her 80

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

Student.includes(:teacher).find(12)
Run Code Online (Sandbox Code Playgroud)

  • 那它在做什么?你可以随时使用旧的方式:`Student.find(12,:include =>:teacher)` (2认同)
  • 它获得了id 12的记录,但没有包含."旧"方式不再适用于3.0.我可以这样工作Student.find_by_id(12).to_json(:include =>:老师)但这不是我想要的 (2认同)

min*_*ank 8

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

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

相反,你可以这样做:

@student = Student.includes(:teacher).where(:id => 12).first
Run Code Online (Sandbox Code Playgroud)

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