如何根据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
答案 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
的用户,请提前道歉。