避免关联查询导致来自不同类型的多个对象的相同记录

时间:2015-12-14 10:11:32

标签: ruby-on-rails ruby-on-rails-4

我有三个模型如下

class Group < ActiveRecord::Base
  has_one :blog
end

class Blog < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :blog
  belongs_to :group
end

group = Group.last
blog = group.blog
comment = blog.comments[0]

每当我写作。

group.blog #firing query 'select * from blogs where group_id = 1 limit 1';

and 

comment.blog # also firing same query 'select * from blogs where group_id = 1 limit 1';

那么,我们怎样才能避免在博客表上重复查询以获取相同的记录(博客)?

1 个答案:

答案 0 :(得分:1)

 class Comment
     belongs_to :blog
     belongs_to :group # this is useless and misleading here
 end

你真正想要的是通过评论的博客获得评论的博客。

 class Group < ActiveRecord::Base
     has_one :blog
 end

 class Blog < ActiveRecord::Base
     belongs_to :group
     has_many :comments
 end

 class Comment < ActiveRecord::Base
     belongs_to :blog
 end

现在只有一种方法可以获取记录:

group = Group.last
blog = group.blog
comment = blog.comments.first

获取评论的小组:

comment.blog.group