how to append data to json in ruby/rails?

后端 未结 6 850
南方客
南方客 2020-12-31 00:29

Say i have this short code:

item = Item.find(params[:id])
render :json => item.to_json

but i needed to insert/push extra information to

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-31 00:59

    The to_json method takes an option object as parameter . So what you can do is make a method in your item class called as message and have it return the text that you want as its value .

    class Item  < ActiveRecord::Base
     def message
      "it works"
     end
    end
    
    render :json => item.to_json(:methods => :message)
    

提交回复
热议问题