Reputation: 406
How can I get the attribute first_name of an entity called Applicant when I'm in a different model called Billing. So far I am able to make it work however, what is returned is the object and not only the attribute.
The following is my code:
class Billing < ActiveRecord::Base
def self.to_csv
attributes=%w{tenant bill_type_dec total_amount created_at datetime_paid paid }
CSV.generate(headers:true) do |csv|
csv<<attributes
all.each do |bill|
csv <<attributes.map{|attr| bill.send(attr)}
end
end
end
def bill_type_dec
if bill_type!=nil
if bill_type==1
"Water"
else
"Electricity"
end
else
"#{description}"
end
end
def tenant
@applicants=Applicant.where(id: tenant_id)
@applicants.each do |appli|
"#{appli.first_name}"
end
end
end
Upvotes: 0
Views: 1344
Reputation: 18130
Or use pluck
and avoid creating the ruby objects
def tenant
Applicant.where(id: tenant_id).pluck(:first_name)
end
BTW - I see you have a tenant_id, if that means you have a belongs_to :tenant
on the Billing class, you will want to pick a different method name (maybe "tenant_first_names"). If this is the case, and tenant has_many :applicants
you can do this:
def tenant_first_names
tenant.applicants.pluck(:first_name)
end
Upvotes: 1
Reputation: 1943
You probably want to use .map
instead of .each
.
You can get all the names of the applicants in an array by doing this:
@applicants.map { |appli| appli.first_name }
#=> ['John', 'Mary']
As you can see, .each
returns the array itself.
.map
will return the array generated by executing the block.
Upvotes: 1