JSON包括条件

我的设置:Rails 2.3.10,Ruby 1.8.7

假设我有这段代码片段

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

如果我想将用户的post包含在某个条件中,例如只有一周的post,该怎么办?

User模型中定义名为week_old_posts的新方法:

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

然后在你的to_json调用中使用methods而不是include

 user.to_json(:methods => :week_old_posts) 

如果要包含整个关联,则:include更有用,如果要包含部分关联,请使用方法。