简体   繁体   中英

How to format nested JSON in Rails?

I am trying to transfer a nested JSON from Rails to JavaScript. So far I successfully transfer following JSON:

[
  "name" : "task-1",
  "relationships" : [
    {"follower": {"name" : "task-2"}},
    {"follower": {"name" : "task-3"}}
]

I would like to format this JSON to look like this:

[
  "name" : "task-1",
  "relationships" : [
    {"name" : "task-2"},
    {"name" : "task-3"}
]

Here is how I generate JSON:

@tasks.to_json(
  :include => { :relationships => {
                  :include => :follower,
                  :only => :follower
               } })

Is there some kind of option that I can specify in my to_json function to get rid off "follower" key name?

Turns out there is. The option is:

ActiveRecord::Base.include_root_in_json = false

You should be able to throw that into config/environment.rb and be good to go.

I ended up using different query to solve the problem:

@tasks = Task.to_json(:include => :followed_tasks)

Where followed_tasks is defined in the Task model:

has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_tasks, through: :relationships, source: :followed

This gives me nicely formatted JSON:

[
  "name" : "task-1",
  "followed_tasks" : [
    { "name" : "task-2" },
    { "name" : "task-3" }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM