Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails how to change attribute name when rendering json?

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?

like image 578
Rails beginner Avatar asked Jan 20 '12 22:01

Rails beginner


2 Answers

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.

like image 185
Rob Davis Avatar answered Nov 05 '22 03:11

Rob Davis


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
like image 34
lucapette Avatar answered Nov 05 '22 04:11

lucapette