Search code examples
ruby-on-railsrails-models

How can I get access to another model class attributes


I have two model class called order.rb and customer.rb:

order.rb

 class Order < ActiveRecord::Base
   belongs_to :customer

validates :customer_id, :name, :age, :presence => true

 def self.to_csv
        attributes = %w{ to_param name age }
        CSV.generate(headers: true) do |csv|
          csv << attributes

              all.each do |t|
                csv << attributes.map{ |attr| t.send(attr) }
          end
        end
      end

customer.rb

class Customer < ActiveRecord::Base
belongs_to :order, primary_key: "customer_id"
has_many :orders

validates :phone_number, :name,:email,:presence => true, allow_blank: true

My question is how do I get the customer.rb data such as it attributes email and name. Then add it to the order.rb data. If you look at the order.rb model I can get its attributes that is listed: name and age, but I am trying to get the customer.rb attributes such as the email, name and phone_number. However, I can get access to one email only if I apply the method display below and it print out the same email over and over again. Thanks in advance if someone can help me.

def to_param
  Customer.new.email
  Customer.all.first.email
end

Solution

  • This will return email ids one after a other -

      Customer.all.each do |customer|
          customer.email 
      end