初期化されていない関連付けを持つ ActiveRecord オブジェクトを返す単純な結合クエリがあり、その理由を理解しようとしています。(私のセットアップ:MySQLを使用したレール2.3.8)
ここに私のモデルがあります:
class Member
has_many :twitter_status_relations
//has some more unrelated associations
end
class TwitterStatus
has_many :twitter_status_relations
end
class TwitterStatusRelation
belongs_to :member
belongs_to :twitter_status
end
そして、ここに私が実行するクエリがあります:
result = TwitterStatusRelation.all(:joins => :twitter_status,
:conditions=>{:twitter_statuses=>{:sent_at=>1.month.ago..DateTime.now}}, :include=>:member,:group=>"twitter_status_relations.member_id")
これで、アプリで初めて実行すると、正常に動作します。
print result[0].member, result[0].member.class.reflect_on_all_associations(:has_many)
#=> <Member...>, [<ActiveRecord::Reflection::AssociationReflection,...]
しかし、もう一度実行してメンバーの関連付けにアクセスしようとすると、nil 例外が発生します。印刷すると次のように表示されます。
print result[0].member, result[0].member.class.reflect_on_all_associations(:has_many)
#=> <Member...>, [-- empty ---]
メンバー オブジェクトには関連付けがないように見えるため、いずれかにアクセスしようとすると例外が発生します。
場合によっては、ActiveRecord が返されたオブジェクトの関連付けを初期化しない理由がわかりますか? 私は立ち往生しているので、半分のアイデアをいただければ幸いです。