ddd
ddd

Reputation: 155

Caching association that was in where clause

Let me show an example:

I have 2 models:

class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :user

  scope :created_in, ->(start_date, end_date) { where(created_at: start_date..end_date) }
end

What I want is to get users that created post during a specific period:

users = User.includes(:posts).joins(:posts).merge(Post.created_in(start_date, end_date))

Is it somehow possible to cache posts that are in the where clause? So after I do

users.first.posts

it will show me exactly those posts that match the condition without producing any additional queries.

Upvotes: 0

Views: 151

Answers (1)

Christian Bruckmayer
Christian Bruckmayer

Reputation: 2187

No, I don't think this is possible. Depending on the context, what you can do is to do a lookup table which you memoize / cache. Something like

User.all.each do |user|
  posts = posts_by_user_id[user.id]
end

def posts_by_user_id
  @_posts_by_user_id ||= posts.group_by(&:user_id)
end

def posts
  Post.created_in(start_date, end_date)
end

Upvotes: 1

Related Questions