ActiveRecord返回具有未初始化关联的模型对象

时间:2011-08-16 14:03:48

标签: ruby-on-rails activerecord ruby-on-rails-2

我有一个简单的连接查询,在某些情况下返回具有未初始化关联的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在某些情况下不会初始化返回对象的关联?我很感激任何半想法,因为我被卡住了。

1 个答案:

答案 0 :(得分:0)

以下是上述查询生成的SQL(Ran代表我发布了问题)。 SQL有更多的字段然后查询,因为我在发布时简化了查询,删除了与问题无关的条件。

SELECT `twitter_status_relations`.`id` AS t0_r0,
     

twitter_status_relationstwitter_status_id AS t0_r1,   twitter_status_relationssource_twitter_identity_id AS t0_r2,   twitter_status_relationsrelation_type AS t0_r3,   twitter_status_relationsrelation_data AS t0_r4,   twitter_status_relationslinked_twitter_identity_id AS t0_r5,   twitter_status_relationsuser_id AS t0_r6,   twitter_status_relationslinked_member_id AS t0_r7,membersid   AS t1_r0,membersuser_id AS t1_r1,membersname AS t1_r2,   membersemail AS t1_r3,membersmember_rating AS t1_r4,   memberscreated_at AS t1_r5,membersupdated_at AS t1_r6,   membersmerged_with_member_id AS t1_r7,membersengage_rating   AS t1_r8,memberssupport_rating AS t1_r9,   membersuser_engage_rating AS t1_r10,   membersuser_support_rating AS t1_r11,   membersinfluence_rating AS t1_r12,memberstwitter_username   AS t1_r13,memberslead_rating AS t1_r14,   membersfollow_rating AS t1_r15,membersunfollow_rating AS   t1_r16,membersfollowers_count AS t1_r17,membershidden AS   t1_r18 FROM twitter_status_relations LEFT OUTER JOIN members ON   members。id = twitter_status_relations。linked_member_id WHERE   (twitter_status_relationsuser_id = 1 AND   twitter_status_relationsrelation_type IN(   '提及','回复','received_dm','转推','链接','术语','#标签')   和twitter_status_relationslinked_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