Imran Ahmad
Imran Ahmad

Reputation: 2927

Inner json objects not rendering Rails

First model:

class AdPlace < ActiveRecord::Base
  belongs_to :user
  has_many :user_ads, dependent: :destroy
  accepts_nested_attributes_for :user_ads, allow_destroy: true, reject_if: :all_blank

   def ad_places_json
    self.as_json(
    include: {
        user_ads: {

        }
    })
  end
end

Second Model:

class UserAd < ActiveRecord::Base
  belongs_to :ad_place
end

From my controller I am trying to get all AdPlaces having all UserAds. So my method of controller is following:

 def get_ads
      ad_places = AdPlace.includes(:user_ads).where(user_id: @current_user.id)
      render json: {
          ad_places: ad_places.each {|ad| ad.ad_places_json},
          message: ['success']
      },
          status: :ok
    end

The above function renders all AdPlaces but UserAds. The SELECT query on server is the following:

  User Load (0.3ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT 1  [["id", 7]]
  AdPlace Load (0.9ms)  SELECT "ad_places".* FROM "ad_places"
  UserAd Load (0.5ms)  SELECT "user_ads".* FROM "user_ads" WHERE "user_ads"."ad_place_id" IN (1, 8, 9, 10, 11, 12, 13)

Everything seems perfect to me, I am confused where am I making mistake. Thank you.

Upvotes: 0

Views: 28

Answers (1)

Roman Kiselenko
Roman Kiselenko

Reputation: 44380

Change each to map:

ad_places.map {|ad| ad.ad_places_json} 

Array#each vs. Array#map

Upvotes: 2

Related Questions