我正在尝试将嵌套的JSON从Rails传输到JavaScript。到目前为止,我成功地传输了以下JSON:
[
"name" : "task-1",
"relationships" : [
{"follower": {"name" : "task-2"}},
{"follower": {"name" : "task-3"}}
]我想将此JSON格式化为如下所示:
[
"name" : "task-1",
"relationships" : [
{"name" : "task-2"},
{"name" : "task-3"}
]下面是我生成JSON的方法:
@tasks.to_json(
:include => { :relationships => {
:include => :follower,
:only => :follower
} })我可以在我的to_json函数中指定一些选项来去掉"follower“键名吗?
发布于 2012-05-11 00:47:44
我最终使用了不同的查询来解决这个问题:
@tasks = Task.to_json(:include => :followed_tasks)其中followed_tasks是在Task模型中定义的:
has_many :relationships, foreign_key: "follower_id", dependent: :destroy
has_many :followed_tasks, through: :relationships, source: :followed这为我提供了格式良好的JSON:
[
"name" : "task-1",
"followed_tasks" : [
{ "name" : "task-2" },
{ "name" : "task-3" }
]发布于 2012-04-15 05:06:40
事实证明是这样的。选项是:
ActiveRecord::Base.include_root_in_json = false您应该能够将其放入config/environment.rb ment.rb中,然后就可以运行了。
https://stackoverflow.com/questions/10155913
复制相似问题