2014-12-19 74 views
0

好的,所以创建了2个模型User和Following。用户具有用户名属性并且以下具有2个用户关联属性:user_id,following_user_id。我在各自的模型中建立了这些关联,并且所有作品都很好。Rails ActiveRecord如何通过自定义命名关联来订购

class User < ActiveRecord::Base 
    has_many :followings, dependent: :destroy 
    has_many :followers, :class_name => 'Following', :foreign_key => 'following_user_id', dependent: :destroy 
end 

class Following < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :following_user, :class_name => 'User', :foreign_key => 'following_user_id' 
end 

现在我需要通过用户名执行ActiveRecord查询时的结果。

Following.where(:user_id => 47).includes(:user).order("users.username ASC") 

问题是我:我可以为直线上升者协会(USER_ID)用下面的代码将返回到我由属于关联的用户名下令追随中的列表,以user_id说明轻松地实现这个无法达到由另一个关联(following_user_id)排序的相同结果。我已经加入该协会的.includes电话,但因为活动记录是寻找在桌子上的关联题为following_users

Following.where(:user_id => 47).includes(:user => :followers).order("following_users.username ASC") 

我试图在.order呼叫改变协会的名字名字,我得到一个错误我在用户模型中作为追随者设置,但没有任何工作,它仍然在寻找具有这些标题的表格。我也尝试了user.username,但是这将基于其他关联进行排序,例如在第一个示例中。

如何通过following_user.username来订购ActiveRecord结果?

回答

2

这是因为您的SQL查询中没有following_users表。

您需要手动加入它像这样:

Following. 
joins(" 
    INNER JOIN users AS following_users ON 
    following_users.id = followings.following_user_id 
"). 
where(user_id: 47). # use "followings.user_id" if necessary 
includes(user: :followers). 
order("following_users.username ASC") 

为了获取没有一个following_user_id,只需使用OUTER JOINFollowing行。

或者,你可以在Ruby中做到这一点,而不是SQL,如果你能承受的速度和内存成本:

Following. 
where(user_id: 47). # use "followings.user_id" if necessary 
includes(:following_user, {user: :followers}). 
sort_by{ |f| f.following_user.try(:username).to_s } 

仅供参考:这try处于失踪following_user的情况下和to_s是确保比较字符串进行排序。否则,nilString相比会崩溃。

+0

工程就像一个魅力!谢谢! –

相关问题