I have a method to_csv
which collect the guest_id from a Booking
table, but instead of returning the guest_id
, i would like to retrieve the first_name
and last_name
as well as the email
from the User
table and put each of them in a row in a csv file.
My method looks as follow:
def self.to_csv
attributes = %w[guest_id]
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |contact|
csv << attributes.map { |attr| contact.send(attr) }
end
end
end
Does anybody know how i could do this please ?
CodePudding user response:
Assume you have the correct one to one user
relation defined in Booking
.
def self.to_csv
attributes = %w[guest_id first_name last_name email]
CSV.generate(headers: true) do |csv|
csv << attributes
all.includes(:user).each do |booking|
csv << [booking.guest_id, booking.user.first_name, booking.user.last_name, booking.user.email]
end
end
end
please note now guest_id
, user.first_name
, user.last_name
, user.email
are in a row. If you want a different format, you can adjust accordingly.