【发布时间】:2014-06-21 08:38:24
【问题描述】:
我是 Rails 新手,在编写 Active Record 查询时,我注意到 all 列的 all 正在检索关联的表。我想告诉 Active Record 应该从哪些表中检索哪些字段。该怎么做呢?
我的模型及其关联如下:
class User < ActiveRecord::Base
has_one :profile
has_many :comments
has_many :posts
end
class Profile < ActiveRecord::Base
belongs_to :user
end
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
end
我正在关注 Rails Edge Guides,当我尝试使用 select("users.id, profiles.first_name, profiles.last_name, comments.comment") 指定字段列表时,我在 Rails 控制台上收到弃用警告(并且运行的 SQL 查询是 LEFT OUTER JOIN涉及的所有表中,但仍包括 所有 列):
DEPRECATION WARNING: It looks like you are eager loading table(s) (one of: users, posts) that are referenced in a string SQL snippet. For example:
Post.includes(:comments).where("comments.title = 'foo'")
Currently, Active Record recognizes the table in the string, and knows to JOIN the comments table to the query, rather than loading comments in a separate query. However, doing this without writing a full-blown SQL parser is inherently flawed. Since we don't want to write an SQL parser, we are removing this functionality. From now on, you must explicitly tell Active Record when you are referencing a table from a string:
Post.includes(:comments).where("comments.title = 'foo'").references(:comments)
If you don't rely on implicit join references you can disable the feature entirely by setting `config.active_record.disable_implicit_join_references = true`. (called from irb_binding at (irb):34)
【问题讨论】:
标签: ruby-on-rails rails-activerecord