gpt4 book ai didi

ruby-on-rails - rails : How to retrieve all model objects along with its foreign relation model with ActiveRecord?

转载 作者:行者123 更新时间:2023-11-29 13:27:09 25 4
gpt4 key购买 nike

我有一个名为 Listing 的模型:

class Listing < ActiveRecord::Base
belongs_to :user
end

我想检索 100 个列表以及每个列表的用户作为列表哈希中的子哈希,所有这些都使用 ActiveRecord 进行一次 SQL 调用。这就是我现在直接使用 PostgreSQL 进行操作的方式:

def listings
listings = ActiveRecord::Base.connection.execute("select row_to_json(t) as listing from (select *, row_to_json(users) as user from listings INNER JOIN users ON listings.user_id = users.id LIMIT 100) t")
render json: {listings:listings,listing_count:Listing.count}
end

没有遍历列表来检索他们的用户,这是非常耗时的。谢谢!

编辑

我按照建议尝试了这个,但它没有返回用户:

  2.2.1 :012 >  Listing.joins(:user).limit(1)
Listing Load (0.6ms) SELECT "listings".* FROM "listings" INNER JOIN "users" ON "users"."id" = "listings"."user_id" LIMIT 1
=> #<ActiveRecord::Relation [#<Listing id: 1, user_id: 1, deleted: false, rent: "$950", deposit: "$950", availability: "6/18/2015", min_duration: "11", male_count: "0", female_count: "1", longitude: "-73.9767700960917", latitude: "40.75831025967895", location: "Midtown Center", comments: "Sequi acidus utor sublime cito autus suasoria. Ips...", photos: "1.jpg, 2.jpg, 3.jpg", cat: false, dog: false, doorman: true, large_room: true, apartment: true, house: false, garden: true, personal_bathroom: false, dog_friendly: true, cat_friendly: false, laundry: false, gym: true, elevator: true, renovated: true, furnished: false, smoking: true, smoke_free: false, air_conditioning: false, utilities_included: true, four_twenty_friendly: false, gay_friendly: false, vegan_friendly: false, vegetarian: true, kosher: false, girls_only: false, guys_only: true, created_at: "2015-07-17 20:09:21", updated_at: "2015-07-17 20:09:21">]>

最佳答案

为什么是单个 SQL 调用?我们是否足以避免 N+1 加载?

时间复杂度差不多(O表示常量):

单个 SQL 调用:1*O(n)两次 SQL 调用:2*O(n)

在这里,O 只是一个不同的常量。就可接受的运行时复杂性而言,因为它仍然是 O(n)。

以此为前提:

听起来您想要做的是预加载 用户关联。你可以这样做:

class Listing < ActiveRecord::Base
belongs_to :user

def self.to_hash_with_user
relation = includes(:user)
relation.map{ |record|
hash = record.as_json
hash['user'] = record.user.as_json
hash
}
end
end

现在你可以这样使用它了

# Get some relation, e.g. Listing.limit(100)
# Because of lazy loading, this will not do a db call yet
listings = Listing.limit(100)
render json: listings.to_hash_with_user.to_json

有关预加载记录的更多信息:http://blog.arkency.com/2013/12/rails4-preloading/

如果您想清理返回的 JSON,并具有更好的结构和灵 active ,我强烈推荐这个 gem:https://github.com/rails-api/active_model_serializers

关于ruby-on-rails - rails : How to retrieve all model objects along with its foreign relation model with ActiveRecord?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31691509/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com