首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据属性的多态关联对Rails模型进行排序

根据属性的多态关联对Rails模型进行排序
EN

Stack Overflow用户
提问于 2014-07-09 07:08:30
回答 1查看 1.8K关注 0票数 4

我想这是一个重复的问题,但我还没有找到它,所以我想我应该问一下。我有一个通过多态关联具有不同类型Profile模型的User模型。类似于:

代码语言:javascript
复制
class User < ActiveRecord::Base
  belongs_to :profile, polymorphic: true
end

class Profile < ActiveRecord::Base
  has_one :user, as: :profile
end

class FacebookProfile < ActiveRecord::Base
  has_one :user, as: :profile
end

我想对User执行一个查询,该查询返回按用户的配置文件对象的名字排序的用户。以前,当没有任何多态关系时,我可以从:profile上的一个joins开始,但我知道这不适用于多态。

除了使用sortsort_by之外,有没有更好的方法来做到这一点:

代码语言:javascript
复制
User.all.sort_by {|user| user.profile.first_name }
EN

回答 1

Stack Overflow用户

发布于 2014-07-22 05:13:47

使用SQL可以做到这一点。

代码语言:javascript
复制
SELECT users.*, COALESCE(profiles.first_name, facebook_profiles.first_name) AS c_first_name FROM users 
LEFT JOIN profiles ON users.profile_id=profiles.id AND users.profile_type="Profile" 
LEFT JOIN facebook_profiles ON users.profile_id=facebook_profiles.id AND users.profile_type="FacebookProfile" 
ORDER BY c_first_name ASC

您应该能够使用这个“手动”连接在User模型上创建一个作用域,因为您可以在两个列上使用COALESCE来创建一个可以排序的别名。

试试这样的东西

代码语言:javascript
复制
class User < ActiveRecord::Base
  belongs_to :profile, polymorphic: true

  scope :sort_by_first_name, -> { select("users.*", "COALESCE(profiles.first_name, facebook_profiles.first_name) AS c_first_name").joins("LEFT JOIN profiles ON users.profile_id=profiles.id AND users.profile_type='Profile'").joins("LEFT JOIN facebook_profiles ON users.profile_id=facebook_profiles.id AND users.profile_type='FacebookProfile'").order("c_first_name ASC") }
end

我自己还没有尝试过,但理论上它应该是有效的。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24642928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档