2013-03-02 1 views
0

Использование Rails 3.2. У меня есть следующий код:Вложенная модель в json in has_many через ассоциацию

# 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

Try ': shop' вместо': shops' в вашем 'методе map_markers' как' DayShop принадлежит к Shop'. –

+0

@SybariteManoj, моя глупая ошибка. Можете ли вы отправить ответ, чтобы я мог отметить его как ответ? Благодаря! – Victor

+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 
Смежные вопросы