我有一个简单的连接查询,在某些情况下返回具有未初始化关联的ActiveRecord对象,我试着理解为什么。 (我的设置:使用MySQL的rails 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,...]
但是,当我再次运行它,并尝试访问该成员的任何关联时,我得到零例外。打印显示以下内容:
print result[0].member, result[0].member.class.reflect_on_all_associations(:has_many)
#=> <Member...>, [-- empty ---]
看起来成员对象没有任何关联,因此当我尝试访问其中任何一个时,我得到一个例外。
您是否知道为什么ActiveRecord在某些情况下不会初始化返回对象的关联?我很感激任何半想法,因为我被卡住了。
答案 0 :(得分:0)
以下是上述查询生成的SQL(Ran代表我发布了问题)。 SQL有更多的字段然后查询,因为我在发布时简化了查询,删除了与问题无关的条件。
SELECT `twitter_status_relations`.`id` AS t0_r0,
twitter_status_relations
。twitter_status_id
AS t0_r1,twitter_status_relations
。source_twitter_identity_id
AS t0_r2,twitter_status_relations
。relation_type
AS t0_r3,twitter_status_relations
。relation_data
AS t0_r4,twitter_status_relations
。linked_twitter_identity_id
AS t0_r5,twitter_status_relations
。user_id
AS t0_r6,twitter_status_relations
。linked_member_id
AS t0_r7,members
。id
AS t1_r0,members
。user_id
AS t1_r1,members
。name
AS t1_r2,members
。members
。member_rating
AS t1_r4,members
。created_at
AS t1_r5,members
。updated_at
AS t1_r6,members
。merged_with_member_id
AS t1_r7,members
。engage_rating
AS t1_r8,members
。support_rating
AS t1_r9,members
。user_engage_rating
AS t1_r10,members
。user_support_rating
AS t1_r11,members
。influence_rating
AS t1_r12,members
。twitter_username
AS t1_r13,members
。lead_rating
AS t1_r14,members
。follow_rating
AS t1_r15,members
。unfollow_rating
AS t1_r16,members
。followers_count
AS t1_r17,members
。hidden
AS t1_r18 FROMtwitter_status_relations
LEFT OUTER JOINmembers
ONmembers
。id =twitter_status_relations
。linked_member_id WHERE (twitter_status_relations
。user_id
= 1 ANDtwitter_status_relations
。relation_type
IN( '提及','回复','received_dm','转推','链接','术语','#标签') 和twitter_status_relations
。linked_member_id
IN( 83995,128457,21421,138316,128455,97475,128453,436231,82236,441208,138564,138337,436223,436222,441093,21194,441088,441092,438998,442752,138331,138327,138325,444897,9277, 12,509521,13,15,534511,7606,7447,200,7,4,17200,5,652302,1,5536,18770,652301,214082,150870,436228,81204,436225,662513,138608,138338 ))和twitter_status_relations
。身份证明(8304,26493,113492,113638, 1,6,41213,113493,20,26173)GROUP BY twitter_status_relations.linked_member_id ORDER BY members.member_rating