Rails选择所有列

时间:2017-12-24 13:39:58

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

我有一个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)?

1 个答案:

答案 0 :(得分:3)

您可以使用两个模型之间的关系并获取所需的用户:

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 ?