开发者

ActiveRecord includes to_json doesn't include relations

开发者 https://www.devze.com 2023-04-10 03:41 出处:网络
I have a model find like this for an API: Article.includes(:comments).all When applying the to_json method, I\'d like to get back the article along with an array of the comments. Unfortunately, the

I have a model find like this for an API:

Article.includes(:comments).all

When applying the to_json method, I'd like to get back the article along with an array of the comments. Unfortunately, the to_json method only开发者_运维知识库 returns the Article model. Help.


use this :

Article.includes(:comments).find(your_article_id).to_json(:include => :comments)

using all on the model will fetch every single article available in the database. using to_json on a relation should get you a json array of all records returned by the relation as json.

you can get additional info here.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号