Ruby on rails 如果我通过另一个父对象创建子对象,那么多个集合方法是否返回空数组

Ruby on rails 如果我通过另一个父对象创建子对象,那么多个集合方法是否返回空数组,ruby-on-rails,associations,belongs-to,Ruby On Rails,Associations,Belongs To,对不起,标题太混乱了,我解释得再清楚不过了。请随意编辑它 我有这样的结构: class Home < ActiveRecord::Base has_many :reservations end class User < ActiveRecord::Base has_many :reservations end class Reservation < ActiveRecord::Base belongs_to :user belongs_to :home end

对不起,标题太混乱了,我解释得再清楚不过了。请随意编辑它

我有这样的结构:

class Home < ActiveRecord::Base
 has_many :reservations

end

class User < ActiveRecord::Base
 has_many :reservations

end

class Reservation < ActiveRecord::Base
 belongs_to :user
 belongs_to :home
end
使用此方法,可以在数据库中正确地创建保留,并且我可以使用该方法检索它(以及用户所做的其余保留)

但是,如果我尝试从用作参数的主实例中检索它,如下所示:

home_instance.reservations 
这将返回一个空数组。相反的情况也会发生(如果我从homes中创建预订,则无法从用户实例中检索预订)

我做错了什么

这两句话不一样吗

Reservation.create(:user => user, :home => home, :other_stuff)
User.reservations.create(:home => home, :other_stuff)

用户模型无法知道您刚刚从主模型创建了预订,反之亦然。当您第一次访问关联时,ActiveRecord会记录该调用的结果,因此不需要在以后每次使用该关联时调用数据库

home_instance.reservations   # This will pull from the databse, and store the
                             # results in a variable.

# This will create a new reservation record in the database.
user_instance.reservations.create(:home => home_instance, :dates_and_other_data => ...)

home_instance.reservations   # We don't go to the database here, since we already
                             # have the stored variable. So we don't see the new
                             # reservation.
您可以通过将
true
作为一个参数传递给一个有许多关联的对象来绕过此问题,如下所示:

home_instance.reservations(true)  # The true forces ActiveRecord to requery the DB>

user_instance.reservations.first.home_id是否指向有效的家?我知道了,谢谢,我不知道。那么,当您将实例分配给变量时,它会第一次检索该信息吗?因为在我的示例中,我没有首先调用收集方法。
home_instance.reservations   # This will pull from the databse, and store the
                             # results in a variable.

# This will create a new reservation record in the database.
user_instance.reservations.create(:home => home_instance, :dates_and_other_data => ...)

home_instance.reservations   # We don't go to the database here, since we already
                             # have the stored variable. So we don't see the new
                             # reservation.
home_instance.reservations(true)  # The true forces ActiveRecord to requery the DB>