使用Rails 3.2。我有以下代码:
# 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
我想要实现的是将shop
模型包装在day_shop
模型(这是一个through
表)中,但当我将其包装在JSON中时,如上所述,我明白了:
undefined method 'shops' for #<DayShop id: 87, day_id: 26, shop_id: 1, position: 1>
我期望的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
如何更改方法?感谢。
答案 0 :(得分:1)
DayShop belongs to a Shop
方法中将shops
加入day_shop
时, map_marker
。将map_marker
修改为:
def map_markers
days.as_json(
:only => :position,
:include => {
:day_shops => {
:only => :position,
:include => {
:shop => {
:only => [ :name ]
}
}
}
}
)
end