Rails 4 - 限制从关联模型中检索的列

时间:2014-06-21 08:38:25

标签: ruby-on-rails rails-activerecord

我是Rails的新手,在编写Active Record查询时,我注意到 所有 所有 正在检索关联的表格。我想告诉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)

2 个答案:

答案 0 :(得分:0)

检查以下是否适合您

Class User < ActivcRecord::Base
   default_scope select("column1, column2, column3")

end

答案 1 :(得分:0)

深埋在Rails Edge Guides内的Active Record Query Interface,我找到了答案。诀窍是将范围用于要限制检索字段的特定关联类型。

直接从指南引用:

  

4.1.3 belongs_to

的范围      

有时您可能希望自定义belongs_to使用的查询。这种定制可以通过示波器块实现。例如:

class Order < ActiveRecord::Base
  belongs_to :customer, -> { where active: true },
                    dependent: :destroy
end
  

您可以使用范围块内的任何标准查询方法。

因此,将select方法添加到上述范围中,并使用您想要检索的字段列表。