Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to return a result to a view where the json does not include the root.

I don't want to set this on all actions for this model,so therefore am trying to avoid setting

ActiveRecord.Base.include_root_in_json = false

I was hoping that I could do

@task = Tasks.all
@task.include_root_in_json = false

To get the response I need, but that doesn't seem to be working, returning an 'undefined method include_root_in_json= for #

Is there a nice way of doing this??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
2.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

It's an old question now, but the answers were not updated, and Rails 3.2 filled the gap (Rails source)

With Rails 3.2, you can now use:

my_model.to_json(:root => false)

if you don't want the root key to be included.

It gets even better as I just tested it with an array, so you can do:

Model.all.to_json(:root => true)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...