在父属性上排序

时间:2014-02-03 07:55:18

标签: ruby-on-rails activerecord

我有一个rails应用程序,用户被分配到项目作为项目用户。现在我想显示一个用户被分配到的项目列表。这有效,但我也想在客户名称和项目名称上进行排序。我怎么能这样做?

因此,客户拥有多个项目,一个项目拥有多个项目用户,一个用户拥有多个项目用户。并且projectuser属于用户和项目。现在我想对customer.name和project.name进行排序。这是ow返回未排序项目的方法:

class User < ActiveRecord::Base
  def active_projects(year=nil, month=nil, day=nil)
    self.projectusers.where("start_date <= ? and (end_date IS NULL or end_date >= ?)",    Date.new(year,month,day).end_of_month, Date.new(year,month,day))
  end
end

我可能需要包含或加入项目和客户?

1 个答案:

答案 0 :(得分:2)

确实,您需要加入项目和客户:

class User < ActiveRecord::Base
  def active_projects(year=nil, month=nil, day=nil)
    self.
      projectusers.
      joins(projects: :customer).
      where("start_date <= ? and (end_date IS NULL or end_date >= ?)", Date.new(year,month,day).end_of_month, Date.new(year,month,day)).
      order("customers.name ASC, projects.name ASC")
  end
end

希望有所帮助

相关问题