您好,我已经搜索过了,但还没有找到执行此操作的方法
我有以下模型:
class Hierarchy < ActiveRecord::Base
belongs_to :user
belongs_to :family
end
.
class Family < ActiveRecord::Base
#attributes rank:integer order:integer
has_many :hierarchies
has_many :users, :through => :hierarchies
end
.
class User < ActiveRecord::Base
has_many :hierarchies
has_many :families, :through => :hierarchies
end
有了 current_user
,我需要获取他的所有其他家庭成员,按级别分组,然后按列顺序排序。
我会说出我尝试过的,但实际上并没有那么多,而且这个查询超出了我的能力范围。 我正在使用 postgres。
最佳答案
我会采用以下方法..
我们必须更新用户模型:)
class User < ActiveRecord::Base
has_many :hierarchies
has_many :families, :through => :hierarchies
has_many :family_members,
-> { group('families.rank').order('families.order ASC') },
through: :families, source: :users
end
然后很容易得到当前用户的所有成员:
current_user.family_members
关于ruby-on-rails - Group by 和 order by 在 Rails 中有很多直通模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26268517/