Rails:如何通过关联的属性名称对属性数组进行排序

时间:2018-08-29 08:04:16

标签: ruby-on-rails ruby sorting

如何根据Person.name排序一个人ID数组,该人ID是从一个与Person模型具有has_many关联并经过GroupParticipation模型的Group模型派生的?

<OpenStruct id=1, name="GroupName", person_ids=[199, 276, 233, 214, 248, 252, 236]>

人员模型:

# Table name: people
#
#  id                          :integer          not null, primary key
#  name                        :string(255)

has_many :groups, through: :group_participations, source: :person_group

人员::小组模型:

# Table name: person_groups
#
#  id                   :integer          not null, primary key
#  name                 :string(255)
#  details              :hstore
#  created_at           :datetime
#  updated_at           :datetime
#  show_job_description :boolean          default(FALSE)

has_many :group_participations, foreign_key: "person_group_id"

has_many :people, through: :group_participations

Person :: GroupParticipation模型

# Table name: person_group_participations
#
#  id                :integer          not null, primary key
#  person_group_id   :integer
#  person_id         :integer
#  created_at        :datetime
#  updated_at        :datetime
#  registration_date :date
#  expiry_date       :date

belongs_to :person belongs_to :person_group, class: Person::Group

ContactsController

> def index
>     @groups = Person::Group.all
>     people_ids = @groups.map(&:person_ids).flatten
>     @people = Person.where(ids: people_ids)   
> end

index.html.slim

   - @groups.each do |group|
     h2 = group.name
     - group.person_ids.each do |id|
       - next if (person = @people.find{|p| p.id == id}).blank?

         details.full-width
         .name= person.name

1 个答案:

答案 0 :(得分:0)

也许尝试(假设您有@group):

@group.people.order(name: :asc).pluck(:id)

为您提供[199, 276, 233, 214, 248, 252, 236]之类的数组。

我确定我误会了一些东西,但是为什么您不做更多类似的事情:

ContactsController

def index
  @groups = Person::Group.all
end

index.html.slim

- @groups.each do |group|
  h2 = group.name
  - group.people.order(name: :asc).each do |person|
    details.full-width
      .name= person.name

如果我搞砸了slim,我自己是haml的用户,请提前道歉。