Ruby on Rails - Add Condition on ':Include =>' to Load Limited Number of Objects

Ruby on Rails - Add condition on ':include =' to load limited number of objects

To my knowledge, you can't use the :include option in the way you describe.

What is your problem with getting all the events anyway? You will have to load/join/query the events table anyway. You will need more memory, though, if you instanciate all events.

Of course you could do two queries, one for the users with the events "today", and one for those without.

You could also go the other way round:

Event.find(:all, :conditions => "...only today...", :include => :user)

Which would give you all events for today with users included. You can use another query to get all users without including the events, and do the rest in memory.

putting a condition on an includes

Finally managed to figure this out from reading this page:
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

I simply needed to create an association in my Post model like:

Post has_many :recent_comments, :class_name = 'Comment', :conditions => ["created_at > ?", 2.weeks.ago]

Then I could do the following to get the desired ActiveRecord::Association object:

category.posts.includes(:recent_comments => :commenters)

There was also a suggestion of doing this by using a scope on a model. However, I read somewhere (I think it was on SO) that scopes are on their way out and that ARel has taken their place so I decided to do this without scopes.

How to limit the number of items that can be added to an ActiveRecord array

You can use a before_add callback (scroll down to heading "Association callbacks") on your association to enforce the behavior

Should any of the before_add callbacks throw an exception, the object does not get added to the collection. Same with the before_remove callbacks; if an exception is thrown the object doesn’t get removed.

Rails 5 - Apply limit to eagerly loaded children of collection

You can add one new association in post model which will fetch only 3 records of comments

has_many :recent_comments, -> { limit(3) }, class_name: 'Comment'

and in controller

@post = Post.includes(:recent_comments)

it won't generate n + 1 query.



Related Topics



Leave a reply



Submit