Rails how to change attribute name when rendering json?

后端 未结 2 647
执念已碎
执念已碎 2021-01-02 17:01

In my controller I have:

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

respond_to do |format|
  format.html # index.html.erb
  format.xml  {          


        
2条回答
  •  自闭症患者
    2021-01-02 17:33

    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.

提交回复
热议问题