วิธีส่งผ่านไปยัง Ruby Map
Oct 09 2020
ฉันมีรหัสต่อไปนี้:
wedding = Wedding.where(location_id: user_params[:locationId])
wedding.map(&:guests).each do |member|
user_ids << member.ids
end
ในกรณีของฉัน:guestsคือตารางบันทึกที่ใช้งานอยู่ แต่ฉันมีสองสามรายการที่ฉันต้องการส่งผ่านmapเพื่อสร้างไฟล์user_ids
ดังนั้นมันจะมีวิธีการมากมายเช่นนี้ที่ฉันต้องการจะผ่าน: [guests, bride, etc etc]
มันจะดีกว่านี้ถ้าฉันสามารถส่งอาร์เรย์ทั้งหมดได้ แต่อย่างอื่นถ้าฉันสามารถก้าวผ่านอาร์เรย์ของวิธีการที่ดีเกินไป
ความคิดใด ๆ ?
แก้ไข: ฉันกำลังลองโดยไม่มีโชค .. ฉันได้รับ: NameError (wrong constant name guests):
roles = ["guests"]
wedding = Wedding.where(location_id: user_params[:locationId])
roles.each do |role|
clazz = Kernel.const_get(role)
wedding.map(&:clazz).each do |member|
user_ids << member.ids
end
end
คำตอบ
2 PhiAgent Oct 09 2020 at 17:46
ด้านล่างนี้ฉันส่งวิธีการมากมายให้กับสมาชิกของงานแต่งงานอาร์เรย์:
weddings = Wedding.where(location_id: user_params[:locationId])
# array with methods you're interested in
methods=[:guests, :bride]
# looping through the weddings array
weddings.each do |wedding|
# looping through the methods array
methods.each do |method|
# for each wedding, passing every method to the wedding
members=wedding.public_send(method)
members.each do |member|
# storing the values
user_ids << member.ids
end
end
end