Ruby on rails 不呈现Rails的内部json对象
第一款:Ruby on rails 不呈现Rails的内部json对象,ruby-on-rails,json,ruby-on-rails-4,Ruby On Rails,Json,Ruby On Rails 4,第一款: 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: {
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
上述函数呈现除用户广告以外的所有广告。
服务器上的SELECT查询如下所示:
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
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)
对我来说,一切似乎都很完美,我不知道我在哪里犯错。
谢谢。将
每个更改为地图:
ad_places.map {|ad| ad.ad_places_json}
将每个更改为地图:
ad_places.map {|ad| ad.ad_places_json}