我有两个模型类叫做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
属性,如电子邮件,姓名和电话号码。 但是,只有当我应用下面的方法显示并且一遍又一遍地打印出同一封电子邮件时,我才可以访问一封电子邮件。如果有人能帮助我,请提前致谢。
def to_param
Customer.new.email
Customer.all.first.email
end
为什么在模型中都有'belongs_to'关联。因为它看起来应该是Customer'has_many'命令。不是吗? – dp7
@dkp我忘了将它添加到我的模型,但我回去改变它。 – user2803053
您已将它添加到'Order'模式中,而应将其添加到'Customer'模型中,像这样'has_many:orders' – dp7