Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON include with conditions

My setup: Rails 2.3.10, Ruby 1.8.7

Let's say I have this code snippet

user = User.find(1)
user.to_json(:include => :posts)

What if I want to include the user's posts with a certain condition like posts that are only a week old?

like image 933
Bob Avatar asked Feb 28 '11 07:02

Bob


1 Answers

Define a new method called week_old_posts in the User model:

def week_old_posts
  posts.where("created_at > ?", 1.week.ago)
end

Then in your to_json call use methods rather than include:

user.to_json(:methods => :week_old_posts)

:include is more useful if you want to include a whole association, use methods for when you want to include parts of associations.

like image 98
Ryan Bigg Avatar answered Sep 17 '22 17:09

Ryan Bigg