ruby on rails:这个sql查询是如何工作的?

时间:2011-07-29 23:45:57

标签: sql ruby-on-rails-3

@posts行究竟做了什么?

def index
    if params[:user_id] && params[:artist_id]
      @id = params[:user_id]
      @name = Artist.find(params[:artist_id]).name
      @posts  = Post.includes(:user).where('users.id' => @id).joins(:artists).where('artists.name' => @name) 
    end
end

它似乎给了我这个非常长的查询:混淆为什么它需要这一切。

由于

Started GET "/users/example4/artists/22/posts" for 127.0.0.1 at 2011-07-29 16:34:48 -0700
      Processing by PostsController#index as HTML
      Parameters: {"user_id"=>"example4", "artist_id"=>"22"}
      Artist Load (0.2ms)  SELECT "artists".* FROM "artists" WHERE "artists"."id" = 22 LIMIT 1
      Post Load (0.5ms)  SELECT "posts"."id" AS t0_r0, "posts"."title" AS t0_r1, "posts"."content" AS t0_r2, "posts"."user_id" AS t0_r3, "posts"."created_at" AS t0_r4, "posts"."updated_at" AS t0_r5, "posts"."item_name" AS t0_r6, "posts"."a_name" AS t0_r7, "posts"."image" AS t0_r8, 
"posts"."collection_id" AS t0_r09, "posts"."featured_post" AS t0_r10, "users"."id" AS t1_r0, 
"users"."email" AS t1_r1, "users"."encrypted_password" AS t1_r2, "users"."reset_password_token" AS 
t1_r3, "users"."remember_token" AS t1_r4, "users"."remember_created_at" AS t1_r5, 
"users"."sign_in_count" AS t1_r6, "users"."current_sign_in_at" AS t1_r7, "users"."last_sign_in_at" 
AS t1_r8, "users"."current_sign_in_ip" AS t1_r9, "users"."last_sign_in_ip" AS t1_r10, 
"users"."created_at" AS t1_r11, "users"."updated_at" AS t1_r12, "users"."name" AS t1_r13, 
"users"."username" AS t1_r14, "users"."bio" AS t1_r15, "users"."avatar" AS t1_r16, 
"users"."cached_slug" AS t1_r17, "users"."bg_image" AS t1_r18, "users"."bg_tile" AS t1_r19 FROM
 "posts" INNER JOIN "artisanships" ON "posts"."id" = "artisanships"."post_id" INNER JOIN "artists" 
ON "artists"."id" = "artisanships"."artist_id" LEFT OUTER JOIN "users" ON "users"."id" = 
"posts"."user_id" WHERE "users"."id" = 0 AND "artists"."name" = 'bobby' ORDER BY posts.created_at 
DESC
      User Load (1.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 7 LIMIT 1
    Rendered posts/artists.html.erb within layouts/application (275.3ms)
    Completed 200 OK in 481ms (Views: 316.4ms | ActiveRecord: 3.4ms)

2 个答案:

答案 0 :(得分:0)

如果您还没有,我建议您阅读AR querying guide

您粘贴的代码来自控制器 - 在该操作中,您要求的是多项内容。这就是为什么要进行多次查询的原因。

这一行:

@name = Artist.find(params[:artist_id]).name

正在查询艺术家表并从结果中获取名称属性

这一行:

@posts  = Post.includes(:user).where('users.id' => @id).joins(:artists).where('artists.name' => @name)

中包含.includes和.joins ...这就是为什么所有查询都是必需的。只要您在表中创建了适当的索引,就不会有问题。

答案 1 :(得分:0)

它正在使用一种名为eager loading的方法。这就是包含的内容。

这意味着什么,而不是你做什么

@posts.first.user

rails再次查询它写入3个查询并调用该帖子的所有用户并将其加载到内存中。这样,当您执行类似

的操作时,可以减少查询计数
@posts.each do |post|
     pusts post.user

联接与SQL联接

相同