将多个连接表作为JSON传递

时间:2015-08-12 20:09:49

标签: ruby-on-rails ruby-on-rails-4

在这个应用程序中,我有4个表(3个对象表和一个交叉引用表):

create_table "businesses", force: :cascade do |t|
  t.string "name", limit: 255, null: false
end

create_table "projects", force: :cascade do |t|
  t.string "name", limit: 255, null: false
  t.integer "status", limit: 4
end

create_table "locations", force: :cascade do |t|
  t.string "name", limit: 255, null: false
  t.integer "business_id", limit: 4, null: false
end

create_table "location_projects", force: :cascade do |t|
  t.integer "project_id", limit: 4
  t.integer "location_id", limit: 4
end

add_index "location_projects", ["project_id"], name: "index_location_projects_on_project_id" using: :btree
add_index "location_projects", ["location_id"], name: "index_location_projects_on_location_id" using: :btree

以下是相应的模型和关联:

class Business < ActiveRecord::Base
  has_many :locations
end

class Location < ActiveRecord::Base
  belongs_to :business
  has_many :location_projects
  has_many :projects, :through => :location_projects
end

class LocationProject < ActiveRecord::Base
  belongs_to :location
  belongs_to :project
end

class Project < ActiveRecord::Base
  has_many :location_projects
  has_many :locations, :through => :location_projects
end

在控制器中,我运行的查询如下:

@locations = Location.joins(:projects, :business).where("projects.status <> 9999")

我在行动的顶部设置repsond_to:json并使用以下命令从动作返回JSON:

respond_with @locations

点击页面时,会生成结果查询(在终端中):

SELECT  `locations`.* FROM `locations` INNER JOIN `location_projects` ON `location_projects`.`location_id` = `locations`.`id` INNER JOIN `projects` ON `projects`.`id` = `location_projects`.`project_id` INNER JOIN `businesses` ON `businesses`.`id` = `locations`.`business_id` WHERE (projects.status <> 9999)

这似乎工作正常。但是,当我调用respond_with @locations时,它只序列化Location记录和Project记录,但不会序列化返回的JSON中的Business记录。

我在这里遗漏了为什么业务没有在JSON响应中返回,但其他两个数据是什么?

2 个答案:

答案 0 :(得分:2)

在序列化时,Rails不会比一个关联更深入。您有两个选择:第一个是覆盖as_json,以便始终返回所需对象的关联。

第二个也是更好的选择,对于复杂的json渲染过程,我建议你使用一个视图,jbuilder就在你身边:你将能够以你想要的方式编写JSON。考虑到它的普通红宝石,如果您不想手动重写每个模型的所有属性,可以使用attributes方法之类的东西。

答案 1 :(得分:0)

您可以使用jbuilder自定义json。

相关问题