避免在Rails中重新加载Activerecord关系

时间:2017-08-21 06:51:08

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

Lats说我有一些关系:

@active_posts = Post.where(active: true).limit(3) # returns 3 active posts, but there are much more then 3 

然后我修改了这种关系的一些成员:

@active_posts.first.update active: false
@active_posts.size # returns 3, but need 2 remaining 

如何在此关系中获得其余2个活动帖子?当我尝试迭代@active_posts时,它将从db重新加载并用活动的post替换已停用的post。但是,我怎么能从这种关系中确切地发现2个活跃的帖子,在停用第三个帖子后仍然存在?

1 个答案:

答案 0 :(得分:0)

使用范围

class Post < ActiveRecord::Base
  scope :actived, -> { where(active: true) }
  scope :deactived, -> { where(active: false) }
end

@active_posts = Post.actived # returns 3 active posts
@active_posts.first.update active: false
@active_posts.reload
@active_posts = Post.actived