属性:は、私は2つのモデルクラスと呼ば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
モデルを見ると、名前と年齢の属性が表示されますが、メール、名前、phone_numberなどの属性はcustomer.rb
になります。 しかし、私は以下の方法の表示を適用して同じ電子メールを何度も繰り返し印刷する場合に限り、1つの電子メールにアクセスできます。誰かが私を助けることができる場合は、事前に感謝します。
def to_param
Customer.new.email
Customer.all.first.email
end
なぜ両方のモデルに 'belongs_to'の関連付けがありますか?それは顧客の 'has_many'注文であるはずです。ではない ? – dp7
@dkp私のモデルに追加するのを忘れましたが、私は戻ってそれを変更します。 – user2803053
これを 'Order'モーダルに追加しました。この' has_many:orders'のように 'Customer'モデルに追加してください。 – dp7