include_root_in_json from controller

后端 未结 2 1814
一生所求
一生所求 2020-12-19 03:15

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

相关标签:
2条回答
  • 2020-12-19 03:26

    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)
    
    0 讨论(0)
  • 2020-12-19 03:46

    From looking at the source for ActiveModel::Serializers::JSON#as_json, it appears there is not a way to change the value of include_root_in_json on a per-method-call basis. Unless I'm missing something, your best recourse is to change the class variable before your call and change it back afterward:

    ActiveRecord::Base.include_root_in_json = false
    render :json => @task
    ActiveRecord::Base.include_root_in_json = true
    

    This is pretty ugly, but it seems that the "include root in json" option wasn't designed with this level of flexibility in mind. It might also cause a race condition with other requests, but I'm not sure about that. Alternatively, you could always keep it set to false, and manually create a hash with a root key in cases where you need that:

    # this case
    render :json => @task
    
    # some other case
    render :json => { :my_model => @my_model.to_json }
    
    0 讨论(0)
提交回复
热议问题