【问题标题】:Rails selecting all columnsRails 选择所有列
【发布时间】:2017-12-24 13:39:57
【问题描述】:

我有一个Article 模型类,它与User 模型建立一对多连接

class Article < ApplicationRecord
  belongs_to :user
end

class User < ApplicationRecord
  has_many :articles
end

当我跑步时

article = Article.find(1)
article.user.username

最后一条语句加载整个表。选择所有列是性能的弊端之一。这是 Rails 控制台输出:

User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]

但我只想要username 列。

有没有办法使用相同的符号 (model_instance.model_instance.column)?

【问题讨论】:

    标签: ruby-on-rails associations rails-activerecord


    【解决方案1】:

    你可以利用两个模型之间的关系,获取需要的User:

    User.select(:name).joins(:articles).find_by(articles: { id: 1 }).username
    # SELECT  "users"."username" FROM "users" INNER JOIN "articles" ON "articles"."user_id" = "users"."id" WHERE "articles"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
    

    也可以写成查询稍作改动:

    User.select(:name).joins(:articles).find_by('articles.id = 1').username
    # SELECT  "users"."username" FROM "users" INNER JOIN "articles" ON "articles"."user_id" = "users"."id" WHERE (articles.id = 1) LIMIT ?  [["LIMIT", 1]]
    

    或者如果使用where,您必须从结果中访问特定记录:

    User.select(:name).joins(:articles).where(articles: { id: 1 }).first.username
    # SELECT  "users"."username" FROM "users" INNER JOIN "articles" ON "articles"."user_id" = "users"."id" WHERE "articles"."id" = ? ORDER BY "users"."id" ASC LIMIT ?
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-24
      • 2023-04-01
      • 2015-01-14
      • 1970-01-01
      • 2016-09-23
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多