Rails how to change attribute name when rendering json?

折月煮酒 提交于 2019-12-30 04:50:08

问题


In my controller I have:

@pakkes = Pakke.where("navn like ?", "%#{params[:q]}%")

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @pakkes }
  format.json { render :json => @pakkes.map(&:attributes) }
end

How do I change the attribute navn to name when rendering JSON?


回答1:


You can do this with a one-line method in Pakke:

def as_json(*args)
    super.tap { |hash| hash["name"] = hash.delete "navn" }
end

Calling super will generate json hash as usual, then before it's returned you'll swoop in and change the key of the "navn" entry.




回答2:


Override the as_json method. It's used by to_json in order to produce the output. You can do something like:

def as_json options={}
 {
   name: navn,
   .... # other attributes you want to add to json
 }
end


来源:https://stackoverflow.com/questions/8948787/rails-how-to-change-attribute-name-when-rendering-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!