如何从ruby on rails入门示例返回JSON

时间:2022-10-24 12:55:27

I am following this really great tutorial. Now I would like to get the comments for a specific posting as JSON output.

我正在学习这个非常棒的教程。现在,我想要得到一个特定发布的注释作为JSON输出。

Doing this for the posting is easy because it is just to call the .json. But how does it work with the comments?

这样做很容易,因为只需调用.json。但是如何处理这些评论呢?

1 个解决方案

#1


1  

So this is mostly sans-code, but the ideas should at least set you in the right direction.

所以这大部分都是无代码,但这些想法至少应该让你找到正确的方向。

To provide comments with their own route, first set up a route for comments in your routes.rb file, then create a show method in the comments controller (similar to the way you set it up for a posting). In the comments controller show method, just render the comment the same way you do for the posting.

要为注释提供自己的路径,首先在您的路径中设置一条注释路径。然后在comments controller中创建一个show方法(类似于为发布设置的方法)。在comments controller show方法中,只需以与post相同的方式呈现注释。

It is a bit easier to just include comments along with the posting when requesting the json output. In the posts controller show method, use render :json => @posting.to_json(:include => :comment) (substitute @posting for the name of the Post object you find in the show method).

在请求json输出时,将注释与发布一起添加进来会更容易一些。在posts控制器show方法中,使用render:json => @post。to_json(:include =>:comment)(用@ Post替换show方法中找到的Post对象的名称)。

#1


1  

So this is mostly sans-code, but the ideas should at least set you in the right direction.

所以这大部分都是无代码,但这些想法至少应该让你找到正确的方向。

To provide comments with their own route, first set up a route for comments in your routes.rb file, then create a show method in the comments controller (similar to the way you set it up for a posting). In the comments controller show method, just render the comment the same way you do for the posting.

要为注释提供自己的路径,首先在您的路径中设置一条注释路径。然后在comments controller中创建一个show方法(类似于为发布设置的方法)。在comments controller show方法中,只需以与post相同的方式呈现注释。

It is a bit easier to just include comments along with the posting when requesting the json output. In the posts controller show method, use render :json => @posting.to_json(:include => :comment) (substitute @posting for the name of the Post object you find in the show method).

在请求json输出时,将注释与发布一起添加进来会更容易一些。在posts控制器show方法中,使用render:json => @post。to_json(:include =>:comment)(用@ Post替换show方法中找到的Post对象的名称)。