Render :json with extra data

前端 未结 3 801
星月不相逢
星月不相逢 2020-12-30 08:43

I have a model called Todo and I render this:

format.json { render :json => @todo }

Each Todo belongs_to a List. I want to add the value

相关标签:
3条回答
  • 2020-12-30 09:04

    You may want to capture the value of the JSON data, and then modify it.

    format.json { render :json => JSON::parse(@todo.to_json).merge("list" => { "completion_percentage" => 63 }).to_json }
    
    0 讨论(0)
  • 2020-12-30 09:19

    To refine Brandon's answer, try using:

    render :json => @todo.attributes.merge({list: { "completion_percentage" => 63 }})
    
    0 讨论(0)
  • Just so others are aware, calling @todo.attributes will pull off custom methods on attributes. E.g., if you have in your Todo model a method

        def written_date
          self.written_date = self.written_date.utc.beginning_of_day
        end 
    

    And an attribute called written_date on the Todo Model, only the attribute will come back that is stored in the database.

    And you except the custom method to come back when you call @todo.attributes, it will not.

    0 讨论(0)
提交回复
热议问题