views:

29

answers:

2

Hi guys, i am trying to display all the residents on a pdf and their dependents, but the dependents doesn't have a stand they are identified by the foreign key user_id of the resident. e.g resident1.id = 5 --- dependent3.user_id = 5 mean dependent3 belongs to resident1, and therefore if i want to display the dependent stand what should i do and i would like to display all the residents and their dependents and the stand information for dependents to be the stand info of the resident the dependent belong to. now my information should be inside a hash so it can generate my pdf file..

my code is

data = [] c = 1 residents.each do |r| data <<{"Fullname" => r.firstname, "Lastname" => r.lastname, "Street-Number" => r.stand.street_no, "street Name" => r.stand.streetname} if r.stand || r.user_id = r.id end

remember my dependents and residents are in the same table but residents doesn't have the user_id foreigh key only the dependent have it.

and my output only display the information of the residents who have stands not the dependents.

please anyone who is willing to help.cause i dont know if i can but an if statement inside a hash like:

residents.each do |r| data <<{"Fullname" => r.firstname, "Lastname" => r.lastname} if r.stand || r.user_id = r.id{"Street-Number" => r.stand.street_no, "street Name" => r.stand.streetname}

A: 
data = []
residents.each do |r|
  tmp_hash = {"Fullname" => r.firstname, "Lastname" => r.lastname}

  if r.stand || r.user_id = r.id
    tmp_hash.merge({"Street-Number" => r.stand.street_no, "street Name" => r.stand.streetname})
  end

  data << tmp_hash

end
Mr. Matt
A: 

Assuming that .stand.street_no, etc. is valid even if .stand is false (since it could be false and still be called if the r.user_id == r.id part is true), then the following would work:

data = residents.map do |r|
  hash = { "Fullname" => r.firstname, "Lastname" => r.lastname }
  hash.merge!({ "Street-Number" => r.stand.street_no, "street Name" => r.stand.streetname}) if r.stand || r.user_id == r.id
  hash
end

Explanation:

  1. Iterate through each resident object and build a hash that contains values that we know will be used.
  2. Conditionally merge! in the extra keys if the if clause is true.
  3. Return the hash.

Doing this in a map eliminates the need to predeclare the data array, nor push the hash on each pass through the loop.

rjk