[英]How to get attribute of object in Model - Ruby on Rails
当我处于名为Billing的其他模型中时,如何获取名为Applicant的实体的first_name属性。 到目前为止,我能够使它工作,但是返回的是对象,而不仅仅是属性。
以下是我的代码:
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
或使用pluck
,避免创建红宝石对象
def tenant
Applicant.where(id: tenant_id).pluck(:first_name)
end
顺便说一句-我看到您有一个tenant_id,如果这意味着您在Billing类上有一个Emirates_to belongs_to :tenant
,您将想要选择一个不同的方法名称(也许是“ tenant_first_names”)。 如果是这种情况,并且租户has_many :applicants
,则可以执行以下操作:
def tenant_first_names
tenant.applicants.pluck(:first_name)
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.