使用 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
我怎样才能改变我的方法?谢谢。