简体   繁体   English

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

[英]How to get attribute of object in Model - Ruby on Rails

How can I get the attribute first_name of an entity called Applicant when I'm in a different model called Billing. 当我处于名为Billing的其他模型中时,如何获取名为Applicant的实体的first_name属性。 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

You probably want to use .map instead of .each . 您可能想要使用.map而不是.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. 如您所见, .each返回数组本身。

.map will return the array generated by executing the block. .map将返回通过执行该块生成的数组。

Or use pluck and avoid creating the ruby objects 或使用pluck ,避免创建红宝石对象

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"). 顺便说一句-我看到您有一个tenant_id,如果这意味着您在Billing类上有一个Emirates_to belongs_to :tenant ,您将想要选择一个不同的方法名称(也许是“ tenant_first_names”)。 If this is the case, and tenant has_many :applicants you can do this: 如果是这种情况,并且租户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