简体   繁体   中英

Accessing data from ActiveRecord

I have a model which has a scope that returns all potentially eligible customers for an automated emailing list; however, there are further checks that are required.

To get the fields needed for the email, I do the following (snippet):

Customers.eligible.each do |customer|
  name: customer.order.first_name
  email: customer.order.contact_info.email
end

I was wonder if there is a nicer way to do this? I'd usually extract the logic into it's own method, eg

def first_name
  customer.order.first_name
end

However, as I have to iterate over each eligible active record, I am unable to do this.

Any ideas? All help is appreciated.

Thanks.

From my personal experience you should be able to able to use the first_name instance method. For the below class method you can definitely evoke the first_name instance method per each customer object.

Customers.eligible.each do |customer|
 name: customer.first_name
 email: customer.order.contact_info.email
end

def first_name
 self.order.first_name
end

Just make sure not to use the instance methods with customer instance which are not eligible for the mail list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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