how to append data to json in ruby/rails?

后端 未结 6 822
南方客
南方客 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:45

    How to append data to json in ruby/rails 5

    If you use scaffold, e.g.:

    rails generate scaffold MyItem
    

    in the view folder you will see next files:

    app/view/my_item/_my_item.json.jbuilder
    app/view/my_item/index.json.jbuilder
    

    so, you can add custom data to json output for an item, just add this:

    json.extract! my_item, :id, :some_filed, :created_at, :updated_at
    json.url my_item_url(my_item, format: :json)    
    
    json.my_data my_function(my_item)
    

    As you can see, it's possible to modify as one item json output, as index json output.

    0 讨论(0)
  • 2020-12-31 00:47

    Have you tried this ?

    item = Item.find(params[:id]) 
    item <<{ :status => "Success" }
    
    render :json => item.to_json
    
    0 讨论(0)
  • 2020-12-31 00:53

    I always use:

    @item = Item.find(params[:id])
    render json: { item: @item.map { |p| { id: p.id, name: p.name } }, message: "it works"  } 
    
    0 讨论(0)
  • 2020-12-31 00:55
    item = Item.find(params[:id])
    item["message"] = "it works"
    render :json => item.to_json
    
    0 讨论(0)
  • 2020-12-31 00:58

    I found the accepted answer now throws deprecation warnings in Rails 3.2.13.

    DEPRECATION WARNING: You're trying to create an attribute message'. Writing arbitrary attributes on a model is deprecated. Please just useattr_writer` etc.

    Assuming you don't want to put the suggested attr_writer in your model, you can use the as_json method (returns a Hash) to tweak your JSON response object.

    item = Item.find(params[:id])
    render :json => item.as_json.merge(:message => 'it works')
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题