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?


Define a new method called week_old_posts in the User model:

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

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.


 ? What's the JSON parser library used in Grails framework?
 ? Getting value from input control using jQuery
 ? Cross-Origin resource sharing and file://
 ? Ruby on Rails JSON serialization
 ? Full MySQL to JSON a Good Thing?
 ? FLASH Bulder Type 1136: Incorrect number of arguments. Expected 2. - JSON
 ? Incrementing value of an object when is called (JS)
 ? Error calling action through getJSON in Asp.Net MVC
 ? JSON Array on Objects to List of String
 ? Deserializing arrays using GSON