Rails 选择所有列
Rails selecting all columns
我有一个 Article
模型 class 与 User
模型
具有一对多连接
class Article < ApplicationRecord
belongs_to :user
end
class User < ApplicationRecord
has_many :articles
end
当我运行
article = Article.find(1)
article.user.username
最后一条语句加载整个 table。选择所有列是性能的缺点之一。这是 Rails 控制台输出:
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
但我只想要 username
列。
有没有办法使用相同的表示法 (model_instance.model_instance.column
)?
您可以使用两个模型之间的关系并获得所需的用户:
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 ?
我有一个 Article
模型 class 与 User
模型
class Article < ApplicationRecord
belongs_to :user
end
class User < ApplicationRecord
has_many :articles
end
当我运行
article = Article.find(1)
article.user.username
最后一条语句加载整个 table。选择所有列是性能的缺点之一。这是 Rails 控制台输出:
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
但我只想要 username
列。
有没有办法使用相同的表示法 (model_instance.model_instance.column
)?
您可以使用两个模型之间的关系并获得所需的用户:
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 ?