Ruby on rails json中的嵌套模型通过多个关联
使用Rails 3.2。我有以下代码:Ruby on rails json中的嵌套模型通过多个关联,ruby-on-rails,json,Ruby On Rails,Json,使用Rails 3.2。我有以下代码: # month.rb class Month < ActiveRecord::Base has_many :days def map_markers days.as_json( :only => :position, :include => { :day_shops => { :only => :po
# month.rb
class Month < ActiveRecord::Base
has_many :days
def map_markers
days.as_json(
:only => :position,
:include => {
:day_shops => {
:only => :position,
:include => {
:shops => {
:only => [ :name ]
}
}
}
}
)
end
end
# day.rb
class Day < ActiveRecord::Base
belongs_to :month
has_many :day_shops
has_many :shops, :through => :day_shops
end
# day_shop.rb
class DayShop < ActiveRecord::Base
belongs_to :day
belongs_to :shop
end
# shop.rb
class Shop < ActiveRecord::Base
end
我期望的JSON是:
- position: 1
:day_shops:
- position: 1
:shops:
- name: Company A
- position: 2
:shops:
- name: Company B
- position: 2
:day_shops:
- position: 1
:shops:
- name: Company A
- position: 2
:shops:
- name: Company C
我怎样才能改变我的方法?谢谢。
DayShop属于一个商店
,而您在地图标记
方法中将商店
包括在DayShop
中。将地图标记修改为:
def map_markers
days.as_json(
:only => :position,
:include => {
:day_shops => {
:only => :position,
:include => {
:shop => {
:only => [ :name ]
}
}
}
}
)
end
尝试
:shop
而不是:shops
在map\u markers
方法中,因为DayShop属于一个shop
@SybariteManoj,我愚蠢的错误。你能把答案贴出来让我把它标记为答案吗?谢谢不客气。完成:)
def map_markers
days.as_json(
:only => :position,
:include => {
:day_shops => {
:only => :position,
:include => {
:shop => {
:only => [ :name ]
}
}
}
}
)
end