新手问题 jbuilder 如何输出 带.的 key

railsweb · 2014年04月15日 · 最后由 railsweb 回复于 2014年04月16日 · 2335 次阅读

比如:{"customer.name":"张三丰"}

用 json.customer.name "张三丰“ 报错 undefined method `name' for #Object:0x007fd9b9c3dfd0

先谢过了。

#1 楼 @cxh116 可以了。谢谢了!

#1 楼 @cxh116 高手,感谢您的指导。再请教一下:我现在改成 json.success true json.data do # json.extract! @customer, :id, :code, :name, :sex, :birthday, :address, :comment json.set! 'customer.id', @customer.id json.set! 'customer.name', @customer.name json.set! 'customer.sex', @customer.sex json.set! 'customer.birthday', @customer.birthday json.set! 'customer.address', @customer.address json.set! 'customer.comment', @customer.comment end 可以输出 {"success":true,"data":{"customer.id":1,"customer.name":"张三丰","customer.sex":"男","customer.birthday":null,"customer.address":"","customer.comment":""}} 就是那个模板 能不能再简化一下啊。每个都要输入 json.set!

你可以自己写一个 helper,写到 application_helper.rb 文件或其它 helper 文件 在里面自己封装一下

def jsonsets(obj, base_name, names)
  names.each do |name|
     json.set! "#{base_name}.#{name}", obj.send(name)
  end
end

#调用
jsonsets(@customer, 'customer', [:id, :name])

#4 楼 @cxh116 真的非常感谢!

#4 楼 @cxh116 不好意思,麻烦又来了,求助: 按照您的方法,提示: undefined local variable or method `json' for #<#Class:0x007fcd58a254b8:0x007fcd5a201410>

函数里的 json.set! json 不识别

#6 楼 @railsweb 把 json 也传过来

def jsonsets(json, obj, base_name, names)
  names.each do |name|
     json.set! "#{base_name}.#{name}", obj.send(name)
  end
end

#调用
jsonsets(json, @customer, 'customer', [:id, :name])

#7 楼 @cxh116 谢谢!代码清爽多了。谢谢!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号