Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.0k views
in Technique[技术] by (71.8m points)

ruby on rails - include_root_in_json from controller

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...