0

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.

0

1 Answer 1

2

Change each to map:

ad_places.map {|ad| ad.ad_places_json} 

Array#each vs. Array#map

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.