第一个模型:
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
第二种模式:
class UserAd < ActiveRecord::Base
belongs_to :ad_place
end
从我的控制器我想让所有AdPlaces都拥有所有UserAds。 所以我的控制器方法如下:
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
上述功能会呈现所有AdPlaces但UserAds。 服务器上的SELECT查询如下:
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)
对我来说一切似乎都很完美,我很困惑我在哪里弄错了。 谢谢。