在 Rails 中,如何使用视图呈现 JSON?

发布于 2024-08-18 10:22:27 字数 566 浏览 9 评论 0原文

假设您在 users 控制器中并且想要获取 show 请求的 json 响应,如果您可以在 views/users/ 目录中创建一个名为 show.json 并在 users#show 之后的文件,那就太好了操作完成,它呈现文件。

目前你需要做一些事情:

def show
  @user = User.find( params[:id] )
  respond_to do |format|
    format.html
    format.json{
      render :json => @user.to_json
    }
  end
end

但是如果你能创建一个 show.json 文件,它会像这样自动渲染,那就太好了:

def show
  @user = User.find( params[:id] )
  respond_to do |format|
    format.html
    format.json
  end
end

这会为我节省大量的悲伤,并且会洗掉我那种可怕的肮脏感觉。当我在控制器中渲染 json 时得到

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.

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:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

嘿哥们儿 2024-08-25 10:22:28

这可能是一个更好的选择,并且比 ERB 更快:https://github.com/dewski/json_builder

This is potentially a better option and faster than ERB: https://github.com/dewski/json_builder

如梦 2024-08-25 10:22:28

我是 RoR 新手,这是我发现的。可以直接渲染json格式

def YOUR_METHOD_HERE
  users = User.all
  render json: {allUsers: users} # ! rendering all users
END

Im new to RoR this is what I found out. you can directly render a json format

def YOUR_METHOD_HERE
  users = User.all
  render json: {allUsers: users} # ! rendering all users
END
云朵有点甜 2024-08-25 10:22:28

我刚刚开始使用 RoR,如果这不是您想要的,我很抱歉。我发现这可能是最新的简单方法,如 https://guides.rubyonrails.org/v5.1/layouts_and_rendering.html#using-render

2.2.8 渲染 JSON

您不需要在要渲染的对象上调用 to_json 。如果您使用 :json 选项,render 会自动为您调用 to_json。

您在 action 中需要做的就是这个

respond_to do |format| 
        format.html
        format.atom
        format.json { render json: @user }
end 

它会在 ./users/1/custom_action.json 中呈现您的 json 响应

I'm just starting out with RoR, my apologies if it's not what you're looking for. I found this and this might be the most up-to-date straightforward method as described in https://guides.rubyonrails.org/v5.1/layouts_and_rendering.html#using-render

2.2.8 Rendering JSON

You don't need to call to_json on the object that you want to render. If you use the :json option, render will automatically call to_json for you.

All you need to do in your action is this

respond_to do |format| 
        format.html
        format.atom
        format.json { render json: @user }
end 

And it renders your json response in ./users/1/custom_action.json

早茶月光 2024-08-25 10:22:27

您应该能够在 respond_to 块中执行类似的操作:

respond_to do |format|
    format.json 
    render :partial => "users/show.json"
end

这将在 app/views/users/_show.json.erb 中呈现模板。

You should be able to do something like this in your respond_to block:

respond_to do |format|
    format.json 
    render :partial => "users/show.json"
end

which will render the template in app/views/users/_show.json.erb.

遮了一弯 2024-08-25 10:22:27

尝试添加一个视图 users/show.json.erb 当您发出 JSON 格式的请求时,应该会呈现该视图,并且您还可以获得由 erb 呈现的额外好处,因此您的文件可以看起来像这样

{
    "first_name": <%= @user.first_name.to_json %>,
    "last_name": <%= @user.last_name.to_json %>
}

(2023 年 1 月 23 日编辑以修复值的双引号)

Try adding a view users/show.json.erb This 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

{
    "first_name": <%= @user.first_name.to_json %>,
    "last_name": <%= @user.last_name.to_json %>
}

(edited Jan 23, 2023 to fix double-quoting on the values)

北座城市 2024-08-25 10:22:27

正如其他人提到的,您需要一个 users/show.json 视图,但是模板语言有一些选项需要考虑...

ERB

开箱即用。非常适合 HTML,但您很快就会发现它对于 JSON 来说很糟糕。

RABL

很好的解决方案。必须添加依赖项并学习其 DSL。

JSON Builder

与 RABL 相同:很好的解决方案。必须添加依赖项并学习其 DSL。

Plain Ruby

Ruby 在生成 JSON 方面非常出色,并且没有什么新东西需要学习,因为您可以在哈希或 AR 对象上调用 to_json。只需注册模板的 .rb 扩展名(在初始值设定项中):

ActionView::Template.register_template_handler(:rb, :source.to_proc)

然后创建视图 users/show.json.rb:

@user.to_json

有关此方法的更多信息,请参阅 http://railscasts.com/episodes/379-template-handlers

As others have mentioned you need a users/show.json view, but there are options to consider for the templating language...

ERB

Works out of the box. Great for HTML, but you'll quickly find it's awful for JSON.

RABL

Good solution. Have to add a dependency and learn its DSL.

JSON Builder

Same deal as RABL: Good solution. Have to add a dependency and learn its DSL.

Plain Ruby

Ruby is awesome at generating JSON and there's nothing new to learn as you can call to_json on a Hash or an AR object. Simply register the .rb extension for templates (in an initializer):

ActionView::Template.register_template_handler(:rb, :source.to_proc)

Then create the view users/show.json.rb:

@user.to_json

For more info on this approach see http://railscasts.com/episodes/379-template-handlers

毁我热情 2024-08-25 10:22:27

如果您正在寻找 ERb 语法的更简洁的替代方案,那么 RABL 可能是我见过的最好的解决方案。 json_builder 和 argonaut 是其他解决方案,它们看起来都有些过时,并且如果不进行一些修补就无法与 Rails 3.1 一起使用。

RABL 可通过 gem 获取或查看 GitHub 存储库;也有很好的例子

https://github.com/nesquena/rabl

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.

RABL is available via a gem or check out the GitHub repository; good examples too

https://github.com/nesquena/rabl

晒暮凉 2024-08-25 10:22:27

只是为了其他碰巧最终出现在该页面上的人而更新此答案。

在 Rails 3 中,您只需在 views/users/show.json.erb 创建一个文件。 @user 对象将可供视图使用(就像 html 一样)。您甚至不再需要 to_json

总而言之,这

# users contoller
def show
  @user = User.find( params[:id] )
  respond_to do |format|
    format.html
    format.json
  end
end

只是

/* views/users/show.json.erb */
{
    "name" : "<%= @user.name %>"
}

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 @user object will be available to the view (just like it would be for html.) You don't even need to_json anymore.

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 %>"
}
你怎么这么可爱啊 2024-08-25 10:22:27

只需添加包含内容的 show.json.erb 文件

<%= @user.to_json %>

有时,当您需要一些控制器中不可用的额外帮助方法时,即 image_path(@user.avatar) 或在 JSON 中生成附加属性的东西:

<%= @user.attributes.merge(:avatar => image_path(@user.avatar)).to_json %>

Just add show.json.erb file with the contents

<%= @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:

<%= @user.attributes.merge(:avatar => image_path(@user.avatar)).to_json %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文