JSON includes conditions

My setup: Rails 2.3.10, Ruby 1.8.7

Say I have this piece of code

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

What should I do if I want to include user messages with a certain condition, for example, messages that are only weeks away?

+4
source share
1 answer

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 , not include :

 user.to_json(:methods => :week_old_posts) 

:include more useful if you want to include the whole association, use methods to include parts of the associations.

+6
source

Source: https://habr.com/ru/post/1341602/


All Articles