Creating an if statement inside a hash in a model
I am trying to display all residents in pdf and their dependents, but the dependents have no rack, which they identify by the external user of the resident's user_id. for example resident1.id = 5 --- dependent3.user_id = 5 mean dependent3 belongs to resident1 and so if I want to display the dependent position what should I do and I would like to display all residents and their dependents and booth information for dependents must have information about the booth of the resident to which the dependent belongs. now my information needs to be inside the hash so that it can generate my pdf file ..
my code
data = [] c = 1 resident.each do | r | data <<{"Full name" => 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 don't have user_id foreigh key only dependents.
and my output only displays information about residents who have no dependents.
please anyone who wants to help. Because I don't know if I can, but an if statement inside a hash like:
resident.each do | r | data <<{"Full name" => 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 source to share
Assuming that .stand.street_no
etc. okay even if it .stand
is false
(since it can be false
and still be called if the part r.user_id == r.id
is true), then the following will 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:
- Iterate through each resident and build a hash that contains the values ββthat we know will be used.
- Conditionally
merge!
in additional keys if the sentence isif
true. - Return hash.
Doing this in map
eliminates the need to pre-glue the array data
or not push the hash every pass through the loop.
a source to share