通过关联在has_many中的json中嵌套模型

时间:2013-03-02 10:06:20

标签: 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 => :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

如何更改方法?感谢。

1 个答案:

答案 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