У меня проблема с ненужным корневым элементом во встроенном объекте 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"
}
Проблема в дублировании ключей 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
благодаря Оливеру Барнсу