如何在 Rails 中的 ruby​​ 中创建复杂的 Json 响应

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6345383/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 01:24:07  来源:igfitidea点击:

How to create complex Json response in ruby in rails

ruby-on-railsrubyjsonruby-on-rails-3

提问by Radio TukTuk

I am working on ruby on rails project and I want to add respond to Json.

我正在研究 ruby​​ on rails 项目,我想添加对 Json 的响应。

One simple way is:--

一种简单的方法是:--

def index
  @users = User.all
  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @users }
    format.json  { render :json => @users.to_json }
  end
end

But there are some issues with this:-

但这有一些问题:-

  1. I don't want to give the whole user object in json response like password hash and cache counter attributes. Facebook, twitter attributes etc.
  2. I want to add more details in the json object (considering stackoverflow model) like Latest question by each user, latest answer given by each user. Instead of image name stored in db via paperclip, I want to pass full url of the image.
  1. 我不想在 json 响应中提供整个用户对象,如密码哈希和缓存计数器属性。Facebook、推特属性等。
  2. 我想在 json 对象(考虑 stackoverflow 模型)中添加更多详细信息,例如每个用户的最新问题,每个用户给出的最新答案。我想传递图像的完整 url,而不是通过回形针存储在 db 中的图像名称。

So the question is how can code json reponse in index.json.erb file like we do in index.html.erb. Format your own json response as per needs.

所以问题是如何在 index.json.erb 文件中编写 json 响应,就像我们在 index.html.erb 中所做的那样。根据需要格式化您自己的 json 响应。

EDIT

编辑

def index
  @users = User.all
  respond_to do |format|
    format.html # index.html.erb
    format.xml  { render :xml => @users }
    format.json  { render :file => "index.json.erb", :content_type => 'application/json' }
  end
end

index.json.erb file:-

index.json.erb 文件:-

    <% @users.each do |user| %>
    {
      first_name: <%= user.first_name %>,
      last_name: <%= user.last_name %>  
    }

    <% end %>

Error:--

错误: -

template missing.

模板丢失。

PS:-- I am just trying using creating this file. This is just a sample

PS:-- 我只是尝试使用创建此文件。这只是一个示例

EDIT

编辑

enter image description here

在此处输入图片说明

edit

编辑

 { { first_name: Mohit , last_name: Jain } { first_name: Sahil Miglani, last_name: } { first_name: Hitesh Bansal, last_name: } { first_name: Sudhanshu, last_name: } { first_name: Saakshi, last_name: } { first_name: Kutta, last_name: } { first_name: bc, last_name: } { first_name: hey, last_name: } { first_name: fewhjfbwfb, last_name: vdsv } } 

EDIT

编辑

    [ { first_name: Mohit , last_name: Jain } , { first_name: Sahil Miglani, last_name: } , { first_name: Hitesh Bansal, last_name: } , { first_name: Sudhanshu, last_name: } , { first_name: Saakshi, last_name: } , { first_name: Kutta, last_name: } , { first_name: bc, last_name: } , { first_name: hey, last_name: } , { first_name: fewhjfbwfb, last_name: vdsv } ] 

EDIT, quite close to find out the solution:-

编辑,非常接近找出解决方案:-

    [
    <% @users.each_with_index do |user,index| %>
    {
        <%= "first_name".to_json.html_safe %>: <%= user.first_name.to_json.html_safe %>,
        <%= "last_name".to_json.html_safe %>: <%= user.last_name.to_json.html_safe %>  
    }
    <% unless index== @users.count - 1%>
    ,
    <% end %>
    <% end %>
    ]

Response:-

回复:-

    [

       -
       {
           first_name: "Mohit "
           last_name: "Jain"
       }
       -
       {
           first_name: "Sahil Miglani"
           last_name: null
       }
       -
       {
           first_name: "Hitesh Bansal"
           last_name: null
       }
       -
       {
           first_name: "Sudhanshu"
           last_name: null
       }
       -
       {
           first_name: "Saakshi"
           last_name: null
       }
       -
       {
           first_name: "Kutta"
           last_name: null
       }
       -
       {
           first_name: "bc"
           last_name: null
       }
       -
       {
           first_name: "hey"
           last_name: null
       }
       -
       {
           first_name: "fewhjfbwfb"
           last_name: "vdsv"
       }

    ]

Now all i want is to enclose this each response section in user array

现在我想要的是将每个响应部分包含在用户数组中

回答by Devin M

You can customize the output by implementing the code in your model:

您可以通过在模型中实现代码来自定义输出:

def as_json(options={})
  super(:only => [:name, :email])
end

Then in your controller you can use:

然后在您的控制器中,您可以使用:

render :json => @user

See "Rails to_json or as_json?" for more info.

有关更多信息,请参阅“ Rails to_json 或 as_json?”。

回答by Andrea Pavoni

You can render a json.erb file and use it like a normal template:

你可以渲染一个 json.erb 文件并像普通模板一样使用它:

# file: app/views/your_controller/your_action.json.erb
{
  filed1: <%= @some_var %>,
  field2: <%= @another_var %>,
  fieldN: <%= @yet_another_var %>,
  data: <%= @some_data.to_json.html_safe %>
}

in your controller, call the explicit render with content_type:

在您的控制器中,调用显式渲染content_type

render :file => "your_file.json.erb", :content_type => 'application/json'

回答by Jesse Wolgamott

You can send options for the JSON format for:

您可以发送 JSON 格式的选项:

  • :only(explicit list of attributes)
  • :except(attribute exclusion list)
  • :methods(list of methods the execute and include their content)
  • :include(relations)
  • :only(属性的显式列表)
  • :except(属性排除列表)
  • :methods(执行的方法列表并包括它们的内容)
  • :include(关系)

If you want to always use this JSON output formatting, put them in the as_jsonmethod (see Devin's answer):

如果您想始终使用此 JSON 输出格式,请将它们放在as_json方法中(请参阅 Devin 的回答):

format.json  { render :json => @users.to_json{:only=>[:name, :email, :id], :methods=>[:last_question_answered], :include=>[:profile] }

回答by JCorcuera

Take a look to rabl gem, to customize your view:

看看rabl gem,自定义您的视图:

# app/views/posts/index.rabl
collection @posts
attributes :id, :title, :subject
child(:user) { attributes :full_name }
node(:read) { |post| post.read_by?(@user) }

That will generate:

这将产生:

[{  post :
  {
    id : 5, title: "...", subject: "...",
    user : { full_name : "..." },
    read : true
  }
}]

回答by Dhruva Sagar

Formatting is the easy part, but I believe what you are asking for, should be achieved within the controller rather than in your view.

格式化是简单的部分,但我相信您所要求的应该在控制器中实现,而不是在您的视图中实现。

Refer to http://ar.rubyonrails.org/classes/ActiveRecord/Serialization.html#M000049and see how you can use to_jsonbetter to actually output just what you need rather than have the entire object serialized.

请参阅http://ar.rubyonrails.org/classes/ActiveRecord/Serialization.html#M000049并了解如何to_json更好地使用来实际输出所需的内容,而不是将整个对象序列化。