Невозможно отобразить внутренние ассоциации при преобразовании в JSON: неявное преобразование символа в целое число - PullRequest
0 голосов
/ 15 октября 2018

Когда я отображаю объект в JSON ниже, он работает нормально:

class Api::ShopsController < ApplicationController
  def show
    shop = Shop.includes(:locations).find(params[:id])

    render json: shop.to_json(include: :locations)
  end
end

Если я пытаюсь отобразить ассоциацию внутри локаций, я получаю сообщение об ошибке:

нетнеявное преобразование символа в целое число

Вот что я пытаюсь сделать:

class Api::ShopsController < ApplicationController
  def show
    shop = Shop.includes(:locations).find(params[:id])
    render json: shop.to_json(include: [locations: [:categories]])

  end
end

Что я здесь не так делаю?

Мои модели:

# == Schema Information
#
# Table name: shops
#
#  id         :bigint(8)        not null, primary key
#  name       :string           not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Shop < ApplicationRecord
  has_many :locations
end


# == Schema Information
#
# Table name: locations
#
#  id         :bigint(8)        not null, primary key
#  shop_id    :integer          not null
#  name       :string
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Location < ApplicationRecord
  belongs_to :shop
  has_many :categories
end


# == Schema Information
#
# Table name: categories
#
#  id          :bigint(8)        not null, primary key
#  shop_id     :integer          not null
#  location_id :integer          not null
#  name        :string           not null
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#

class Category < ApplicationRecord
  belongs_to :shop
  belongs_to :location
  has_many :category_products
end

# == Schema Information
#
# Table name: category_products
#
#  id          :bigint(8)        not null, primary key
#  category_id :integer          not null
#  product_id  :integer          not null
#  sort_order  :integer          not null
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#

class CategoryProduct < ApplicationRecord
  belongs_to :category
  belongs_to :product
end

1 Ответ

0 голосов
/ 15 октября 2018

Согласно документам to_json, чтобы включить ассоциации 2-го уровня и высшего порядка, вы должны сделать, как показано ниже

render json: shop.to_json(include: {locations: { include: {:categories}}})

Обновление:

Приведенный выше фрагмент кода не работает, поэтому я предложил другой подход.Это должно работать

render json: shop.to_json(:include => [locations: {include: [:categories]}])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...