繁体   English   中英

如何在模型中获取对象的属性-Ruby on Rails

[英]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

您可能想要使用.map而不是.each

通过执行以下操作,可以获取数组中所有申请人的姓名:

@applicants.map { |appli| appli.first_name }

#=> ['John', 'Mary']

如您所见, .each返回数组本身。

.map将返回通过执行该块生成的数组。

或使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM