8

埋め込まれた json オブジェクトの不要なルート要素に問題がありました。クリーンなソースは次のとおりです。

ユーザーモデル:

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

コントローラのアクション 'new'

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"
}

問題は、credit_card キーの重複にあります。どうすれば解決できますか?


最終的解決:

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

オリバー・バーンズに感謝

4

1 に答える 1

11

試す

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
于 2011-04-01T02:53:23.710 に答える