Ruby on Rails Advanced JSON Serialization

前端 未结 7 953
闹比i
闹比i 2020-12-13 02:53

I\'m looking to render an index of all articles along with a full article via JSON in my rails app, but I\'m having a little trouble figuring out how to do it.

Here

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-13 03:13

    (Please accept an answer)

    I think that the link that nirvdrum gave holds your answer. I only answer because nobody has mentioned encode_json.

    In your case you should only be dealing with as_json. Either by building a hash (with various calls to as_json) and sending that to render :json => ... (without the call to to_json) or by simply implementing as_json on your model and letting rails do all the work. (But I suspect you'll need the former.)

    If you really need some fancy js in your rendered response then you can implement encode_json in your classes (again, not to_json). For example:

    class JsEmptyClosure
      def encode_json(*args)
        "jQuery[\"noop\"] || function(){}"
      end
      def as_json(*args) self end
    end
    

    This will now respond to to_json with valid js (but note it's not actually json).

提交回复
热议问题