简体   繁体   中英

Get value of attribute when iterating over array of objects (getting nils)

In my Guest model, I have this method to return a list of ids from an associated model:

def self.people_list(consultant_id)
  # returns an array of ids of people who attended parties for a given consultant
  people = self.select(:person_id).joins('INNER JOIN parties ON guests.party_id = parties.id').where('parties.consultant_id = ?', consultant_id).collect{ |g| g.person_id }
end

person_id is a field in the Guest model. But what I'm getting back is an array of nils. From rails console I can tell that the query is correct, and it is returning the correct number of objects. I'm just not getting them into the array.

Thank you for you help.

PS, In case it helps/matters, Consultants have many Parties, which have many Guests. The Guests has a person_id, which joins to the People table. I'm trying to find all the person_ids from the Guests table that have been to a party for a given consultant.

From the console (after changing to rails associations syntax as noted below)

Guest Load (0.3ms)  SELECT person_id FROM `guests` INNER JOIN `parties` ON `parties`.`id` = `guests`.`party_id` WHERE (parties.consultant_id = 1)
=> [nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil] 

In my opinion you should approach this as the consultant being the primary object.

def attendees
  @attendees = []
  parties.each do |p|
    @attendees << p.guests.collect(&:person_id)
  end
  @attendees
end

Then call that method on the consultant object.

So, I realized I had attr_accessor on :people_id, which is what caused the nils. I need to leave that in for another party of the system, but I was able to get the correct values by replacing g.person_id with g[:person_id].

I don't quite understand why, but it works...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM