你好,我在我的项目中有这个模型,大学1-N城市N-N运营商,所以,一个运营商可以出现在许多城市,一个城市有许多运营商。
我的模型:
University.rb
class University < ActiveRecord::Base
has_many :sedes
end
City.rb
class Sede < ActiveRecord::Base
belongs_to :university
has_and_belongs_to_many :carrers
end
Carrer.rb
class Carrer < ActiveRecord::Base
has_and_belongs_to_many :cities
end然后,我创建了一个迁移"CitiesCarrers“来保存数据库关系N-N
class CreateCitiesCarrers < ActiveRecord::Migration
def change
create_table :cities_carrers, :id => false do |t|
t.references :city
t.references :carrer
end
add_index :cities_carrers, :city_id
add_index :cities_carrers, :carrer_id
end
end那么,我如何在城市中展示json,与之相关的运营商呢?
in my CitiesController
def index
render json: {cities: City.all, carrers: Carrer.all }, methods: {:university_id :carrer_id }
end我把":carrer_id“和app crush放在那里,但如果我在展示城市时绘制它,carreers就在blak中。
我们能帮我吗?谢谢
发布于 2015-11-25 01:36:34
render json: { City.all, include: [:carrers] }如果你有一个来自索引方法的@cities实例变量,你可以这样做...
render json: { @cities, include: [:carrers] }而且,出于性能原因,请执行以下操作
City.include(:carrers) # 'include' to avoid n+1 query.https://stackoverflow.com/questions/33899268
复制相似问题