Вопрос

I have 2 very simple models:

class Teacher < ActiveRecord::Base
  has_one :fee, :foreign_key => 'teacher_id'
end

...

class Fee < ActiveRecord::Base
  belongs_to :teacher
end

When loading teacher information with the "find" method, only teacher table information are present. (data exists in the fee table)

@teacher = Teacher.find(id)

With the debug method :

--- !ruby/object:Teacher
attributes:
  id: 7
   …
  presentation: 
  presentation_flag: true
  created_at: 2013-09-16 00:38:14.000000000 Z
  updated_at: 2013-09-16 00:38:14.000000000 Z
  status: 
  last_login: 
  first_name: 
…

But nothing about fee table. Any ideas ? Thank you

Это было полезно?

Решение

This is by design. ActiveRecord is 'lazy' by default, it only fetches the fee data when you access @teacher.fee for the first time.

In case you want to load both at the same time, you should use 'eager loading' by adding includes like this:

@teacher = Teacher.includes(:fee).find(id)

Here are a couple of references for 'eager loading':

http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations http://railscasts.com/episodes/22-eager-loading-revised

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top