我在嵌入式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 %>
当我保存用户app时发送下一个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
感谢Oliver Barnes