2013-03-02 61 views
0

使用Rails 3.2。我有以下代碼:通過關聯在has_many中嵌套json模型

# 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 

我所試圖實現的是包裹在day_shop模型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

嘗試':shop'而不是':shops'在'map_markers'方法作爲'DayShop屬於Shop'。我的愚蠢的錯誤是@SybariteManoj @ – 2013-03-02 10:18:10

+0

。你能發表一個答案,以便我可以將其標記爲答案嗎?謝謝! – Victor 2013-03-02 10:26:22

+0

不客氣。完成:) – 2013-03-02 10:46:01

回答

1

DayShop belongs to a Shop,而你是其​​中shopsday_shopmap_marker方法。修改map_marker到:

def map_markers 
    days.as_json(
    :only => :position, 
    :include => { 
     :day_shops => { 
     :only => :position, 
     :include => { 
      :shop => { 
      :only => [ :name ] 
      } 
     } 
     } 
    } 
) 
end 
相關問題