Ruby-on-rails 在 Rails 中,如何使用视图呈现 JSON?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2088280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Rails, how do you render JSON using a view?
提问by Matthew
Suppose you're in your users controller and you want to get a json response for a show request, it'd be nice if you could create a file in your views/users/ dir, named show.json and after your users#show action is completed, it renders the file.
假设你在你的用户控制器中并且你想获得一个显示请求的 json 响应,如果你能在你的视图/用户/目录中创建一个文件,命名为 show.json 并在你的 users#show 之后,那就太好了操作完成,它呈现文件。
Currently you need to do something along the lines of:
目前你需要做一些事情:
def show
@user = User.find( params[:id] )
respond_to do |format|
format.html
format.json{
render :json => @user.to_json
}
end
end
But it would be nice if you could just create a show.json file which automatically gets rendered like so:
但是,如果您可以创建一个 show.json 文件,该文件会像这样自动呈现,那就太好了:
def show
@user = User.find( params[:id] )
respond_to do |format|
format.html
format.json
end
end
This would save me tons of grief, and would wash away that horribly dirty feeling I get when I render my json in the controller
这将为我节省大量的悲伤,并且会消除我在控制器中呈现我的 json 时的那种可怕的肮脏感觉
采纳答案by Alex Reisner
You should be able to do something like this in your respond_toblock:
你应该能够在你的respond_to块中做这样的事情:
respond_to do |format|
format.json
render :partial => "users/show.json"
end
which will render the template in app/views/users/_show.json.erb.
这将在app/views/users/_show.json.erb.
回答by erik
Try adding a view users/show.json.erbThis should be rendered when you make a request for the JSON format, and you get the added benefit of it being rendered by erb too, so your file could look something like this
尝试添加一个视图users/show.json.erb这应该在您请求 JSON 格式时呈现,并且您也可以获得由 erb 呈现的额外好处,因此您的文件可能看起来像这样
{
"first_name": "<%= @user.first_name.to_json %>",
"last_name": "<%= @user.last_name.to_json %>"
}
回答by tybro0103
As others have mentioned you need a users/show.json view, but there are options to consider for the templating language...
正如其他人提到的,您需要一个 users/show.json 视图,但是模板语言有一些选项需要考虑......
ERB
再培训局
Works out of the box. Great for HTML, but you'll quickly find it's awful for JSON.
开箱即用。非常适合 HTML,但您很快就会发现它对于 JSON 来说很糟糕。
Good solution. Have to add a dependency and learn its DSL.
很好的解决方案。必须添加一个依赖项并学习它的 DSL。
Same deal as RABL: Good solution. Have to add a dependency and learn its DSL.
与 RABL 相同的交易:很好的解决方案。必须添加一个依赖项并学习它的 DSL。
Plain Ruby
纯红宝石
Ruby is awesome at generating JSON and there's nothing new to learn as you can call to_jsonon a Hash or an AR object. Simply register the .rb extension for templates (in an initializer):
Ruby 在生成 JSON 方面非常出色,而且没有什么新东西需要学习,因为您可以调用to_jsonHash 或 AR 对象。只需为模板注册 .rb 扩展名(在初始化程序中):
ActionView::Template.register_template_handler(:rb, :source.to_proc)
Then create the view users/show.json.rb:
然后创建视图 users/show.json.rb:
@user.to_json
For more info on this approach see http://railscasts.com/episodes/379-template-handlers
有关此方法的更多信息,请参阅http://railscasts.com/episodes/379-template-handlers
回答by zapnap
RABL is probably the nicest solution to this that I've seen if you're looking for a cleaner alternative to ERb syntax. json_builder and argonaut, which are other solutions, both seem somewhat outdated and won't work with Rails 3.1 without some patching.
如果您正在寻找 ERb 语法的更干净的替代方案,RABL 可能是我见过的最好的解决方案。json_builder 和 argonaut 是其他解决方案,它们似乎都有些过时,如果不打补丁就无法与 Rails 3.1 一起使用。
RABL is available via a gem or check out the GitHub repository; good examples too
RABL 可通过 gem 获得或查看 GitHub 存储库;也是很好的例子
回答by James Lim
Just to update this answer for the sake of others who happen to end up on this page.
只是为了其他碰巧最终出现在此页面上的人更新此答案。
In Rails 3, you just need to create a file at views/users/show.json.erb. The @userobject will be available to the view (just like it would be for html.) You don't even need to_jsonanymore.
在 Rails 3 中,你只需要在views/users/show.json.erb. 该@user对象将可用于视图(就像用于 html 一样。)您甚至to_json不再需要了。
To summarize, it's just
总结一下,这只是
# users contoller
def show
@user = User.find( params[:id] )
respond_to do |format|
format.html
format.json
end
end
and
和
/* views/users/show.json.erb */
{
"name" : "<%= @user.name %>"
}
回答by Priit
Just add show.json.erbfile with the contents
只需添加show.json.erb包含内容的文件
<%= @user.to_json %>
Sometimes it is useful when you need some extra helper methods that are not available in controller, i.e. image_path(@user.avatar)or something to generate additional properties in JSON:
有时,当您需要一些控制器中不可用的额外帮助方法时,它很有用,即image_path(@user.avatar)或在 JSON 中生成其他属性的东西:
<%= @user.attributes.merge(:avatar => image_path(@user.avatar)).to_json %>
回答by PETER BROWN
This is potentially a better option and faster than ERB: https://github.com/dewski/json_builder
这可能是比 ERB 更好且更快的选择:https: //github.com/dewski/json_builder
回答by aRtoo
Im new to RoR this is what I found out. you can directly render a json format
我是 RoR 的新手,这就是我发现的。可以直接渲染json格式
def YOUR_METHOD_HERE
users = User.all
render json: {allUsers: users} # ! rendering all users
END

