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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With