JSON包含条件 [英] JSON include with conditions

查看:192
本文介绍了JSON包含条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的设置:Rails 2.3.10,Ruby 1.8.7

My setup: Rails 2.3.10, Ruby 1.8.7

假设我有此代码段

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?

推荐答案

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

Define a new method called week_old_posts in the User model:

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

然后在您的to_json通话中使用methods而不是include:

Then in your to_json call use methods rather than include:

user.to_json(:methods => :week_old_posts)

:include如果要包括整个关联,则在要包括部分关联时使用方法.

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

这篇关于JSON包含条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆