Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails json中的嵌套模型通过多个关联_Ruby On Rails_Json - Fatal编程技术网

Ruby on rails json中的嵌套模型通过多个关联

Ruby on rails json中的嵌套模型通过多个关联,ruby-on-rails,json,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 => :po

使用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
我期望的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

我怎样才能改变我的方法?谢谢。

DayShop属于一个商店
,而您在
地图标记
方法中将
商店
包括在
DayShop
中。将地图标记修改为:

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

尝试
:shop
而不是
:shops
map\u markers
方法中,因为
DayShop属于一个shop
@SybariteManoj,我愚蠢的错误。你能把答案贴出来让我把它标记为答案吗?谢谢不客气。完成:)
def map_markers
  days.as_json(
    :only => :position,
    :include => {
      :day_shops => { 
        :only => :position, 
        :include => {
          :shop => {
            :only => [ :name ]
          }
        }
      }
    }
  )
end