Ruby on Rails Wednesday, November 26, 2014



On Wednesday, November 26, 2014 6:57:37 PM UTC+8, Colin Law wrote:
On 26 November 2014 at 08:03, Zhao Difei <dif...@gmail.com> wrote:
> Greetings all,
>
>   I have a json object (text) to render, formatted as:
>
> {
> "a": "b",
> "c":
> [ { "id": "abracadabra",
> "data": "good" }
> { "id": "abracxxabra",
> "data": "goodsss" } ]
> }
>
>   How could exclude the id fields from rendering, I tried different
> combinations:
>
> render json: obj, except: [ c: [ "id" ] ]
> render json: obj, include: [ c: [ except: "id" ] ]
>
>   none of them works, any ideas? Thanks in advance.

If your json object is actually an ActiveRecord object (or maybe more
correctly ActiveModel) and you always want these objects to render in
a particular way, then you can override as_json to achieve this.  Then
using render json to serialise it will use use overridden as_json,
where you can include whichever bits (including calculated values)
that you desire.
I in fact I already override two methods of mongoid to do this, but I still have some json strings to render, which is not very handy if I cannot use the "render :except" method.

Colin

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/34714056-5b3e-4dd2-a105-f03bcd0899c6%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment