Sea*_*yar 2 sorting activerecord ruby-on-rails pluck
在我的侧边栏中,我显示了新创建的用户配置文件.个人资料belongs_to
用户和用户has_one_profile
.我意识到我只使用配置文件表中的3列,所以最好使用pluck.我也有link_to user_path(profile.user)
部分,所以我不得不告诉用户是谁.目前我正在使用includes
,但我不需要整个用户表.所以我使用了来自用户和配置文件表的许多列.
如何用拔毛来优化它?我尝试了几个版本,但总是遇到一些错误(大部分时间都没有定义profile.user).
我目前的代码:
def set_sidebar_users
@profiles_sidebar = Profile.order(created_at: :desc).includes(:user).limit(3) if user_signed_in?
end
create_table "profiles", force: :cascade do |t|
t.integer "user_id", null: false
t.string "first_name", null: false
t.string "last_name", null: false
t.string "company", null: false
t.string "job_title", null: false
t.string "phone_number"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
t.string "avatar"
t.string "location"
end
Run Code Online (Sandbox Code Playgroud)
好吧,让我们解释三种不同的方式来完成你正在寻找的东西.
首先,它们之间存在差异,includes
并且joins
只包含了与所有指定的关联列的关联.它不允许您从两个表中查询或选择多个列.它做joins
什么.它允许您查询两个表并选择您选择的列.
def set_sidebar_users
@profiles_sidebar = Profile.select("profiles.first_name,profiles.last_name,profiles.id,users.email as user_email,user_id").joins(:user).order("profile.created_at desc").limit(3) if user_signed_in?
end
Run Code Online (Sandbox Code Playgroud)
它将返回Profiles
包含您在select
子句中提供的所有列的关系.您可以像对配置文件对象一样获取它们e-g
@profiles_sidebar.first.user_email
将为您提供此个人资料的用户电子邮件.
如果要查询多个表或想从两个表中选择多个列,则此方法最佳.
2.Pluck
def set_sidebar_users
@profiles_sidebar = Profile.order(created_at: :desc).includes(:user).limit(3).pluck("users.email,profiles.first_name") if user_signed_in?
end
Run Code Online (Sandbox Code Playgroud)
Pluck仅用于从多个关联中获取列,但它不允许您使用的权力ActiveRecord
.它只是以相同的顺序返回所选列的数组.就像在第一个例子中一样,你可以获得用户的配置文件对象@profiles_sidebar.first.user
但是你可以不用它,因为它只是一个普通的数组.这就是为什么你的大多数解决方案都会引发错误的原因profile.user is not defined
现在这是选项三.在第一个解决方案中,您可以在两个表上获得多个列并使用它的强大功能,ActiveRecord
但它并不急于加载关联.因此,如果循环返回结果的关联,它仍然会花费N + 1个查询 @profiles_sidebar.map(&:user)
因此,如果您想使用includes
但想要使用所选列,那么您应该与所选列建立新关联并调用该关联.例如,在profile.rb
belongs_to :user_with_selected_column,select: "users.email,users.id"
Run Code Online (Sandbox Code Playgroud)
现在您可以将它包含在上面的代码中
def set_sidebar_users
@profiles_sidebar = Profile.order(created_at: :desc).includes(:user_with_selected_column).limit(3) if user_signed_in?
end
Run Code Online (Sandbox Code Playgroud)
现在这将急切加载用户,但将只选择用户的电子邮件和ID.可以在ActiveRecord包含更多信息 .指定包含的列
UPDATE
当你问起采摘的优点时,让我们解释一下.如您所知,pluck
返回普通数组.因此它不会实例化ActiveRecord对象,它只返回从数据库返回的数据.因此,最好在不需要ActiveRecord对象的地方使用pluck,而只是以表格形式显示返回的数据.选择返回关系,以便您可以进一步查询它或在其实例上调用模型方法.因此,如果我们总结它,我们可以说
模型值的选择,选择模型对象
有关更多信息,请访问http://gavinmiller.io/2013/getting-to-know-pluck-and-select/
归档时间: |
|
查看次数: |
3890 次 |
最近记录: |