【问题标题】:Disable json root element in embedded objects on ActiveResource query在 ActiveResource 查询中禁用嵌入对象中的 json 根元素
【发布时间】:2011-03-31 11:48:47
【问题描述】:

我遇到了嵌入 json 对象中不必要的根元素的问题。 这是清理后的来源:

用户模型:

class User < ActiveResource::Base
      self.format = :json
      self.element_name = "user"
      #...
end

控制器的动作“新”

def new
 @user = User.build
 @user.id = nil
end

User.build 给了我下一个 json:

{
  "id":0,
  "user_name":null,
  "credit_card":
    {"number":null}
}

控制器的操作“创建”

def create
    @user = User.new(params[:user])
    @user.save
end

查看'_form.html.erb'

<%= form_for(@user) do |f| %>
    <%= f.label :user_name %>
    <%= f.text_field :user_name %>

        <%= f.fields_for @user.credit_card do |cc_f| %>
            <%= cc_f.label :number %>
            <%= cc_f.text_field :number %>
        <% end %>
<% end %>

当我保存用户应用时发送下一个 json:

{
 "user"=>
   {"credit_card"=>
     {"credit_card"=>
       {"number"=>"xxxxyyyyzzzzaaaa"}
     }, 
   "user_name"=>"test"
    }, 
 "api_client_key"=>"top_secret"
}

问题在于信用卡密钥重复。我该如何解决?


最终解决方案:

class User < ActiveResource::Base
      self.include_root_in_json = false
      self.format = :json
      self.element_name = "user"

      def to_json(options = {})
          {
             self.class.element_name => self.attributes
          }.to_json(options)
      end
# ...
end

感谢奥利弗·巴恩斯

【问题讨论】:

    标签: ruby-on-rails json ruby-on-rails-3 activeresource


    【解决方案1】:

    试试

    ActiveResource::Base.include_root_in_json = false
    

    如果您需要保留顶级根并仅删除关联的信用卡对象的根,那么您可能需要使用#to_json 自定义 json 输出,如下所示:

    def to_json(options = {})
      { "user"=>
          {"credit_card"=>
            {"number"=> self.credit_card.number }
           }, 
            "user_name"=> self.user_name
       }.to_json(options)
    end
    

    【讨论】:

    • 如果问题是关于 ActiveResource 为什么要使用 ActiveRecord?
    • ActiveResource 具有相同的参数。但它也删除了“用户”元素。
    • @Fivell 深夜回答,修复它
    • @mind.debug,如果您需要顶级根而不需要关联的根,您可能需要使用 as_json 自定义输出。立即将此添加到答案中
    • include_root_in_json = false 救了我!非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2016-03-04
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 2013-03-18
    • 1970-01-01
    • 2023-03-11
    • 2016-05-05
    相关资源
    最近更新 更多