如何访问其他模型类属性

时间:2016-04-03 02:00:01

标签: ruby-on-rails rails-models

我有两个名为order.rb和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

我的问题是如何获取customer.rb数据,例如属性电子邮件和名称。然后将其添加到order.rb数据中。如果您查看order.rb模型,我可以获取列出的属性:名称和年龄,但我尝试获取customer.rb属性,例如电子邮件,姓名和phone_number。 但是,只有在我应用下面的方法显示并且一遍又一遍地打印出相同的电子邮件时,我才能访问一封电子邮件。如果有人可以帮助我,请提前感谢。

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

2 个答案:

答案 0 :(得分:0)

这将一个接一个地返回电子邮件ID -

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

答案 1 :(得分:0)

class Order < ActiveRecord::Base
  belongs_to :customer

  def self.to_csv
    attributes = %w{ phone_number name age }
    CSV.generate(headers: true) do |csv|
      csv << attributes
      all.each do |t|
        # Note: Considering the attributes are defined in `Customer` model. 
        #   It will get the `customer` of every order and send the message like 
        #     `email`, `name` and maps the responses to the messages
        csv << attributes.map { |attr| t.customer.send(attr) }
      end
    end
  end
end

class Customer < ActiveRecord::Base
  has_many :orders

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

如果Order模型中的所有属性都不可用,那么您可以将缺少的属性委托给Customer模型。

# in order.rb    
deligate :name, :email, :phone_number, to: :customer, allow_nil: true

# Then this will work; no need of `.customer` as message will be delegated
csv << attributes.map { |attr| t.send(attr) }

:allow_nil - 如果设置为true,则阻止引发NoMethodErrorSee this for more info about delegation

如果需要进一步的帮助,请在此处评论。