2016-04-03 5 views
0

属性:は、私は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 
+0

なぜ両方のモデルに 'belongs_to'の関連付けがありますか?それは顧客の 'has_many'注文であるはずです。ではない ? – dp7

+0

@dkp私のモデルに追加するのを忘れましたが、私は戻ってそれを変更します。 – user2803053

+0

これを 'Order'モーダルに追加しました。この' has_many:orders'のように 'Customer'モデルに追加してください。 – dp7

答えて

0

これは、電子メールのIDを1つずつ返します -

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

上記のコードを実行すると、名前、電子メール、電話番号などのすべての属性が返されます。また、電子メールidsを次々と返すこともありません。これは、テーブルの各スロットにあるすべての電子メールを返します。 – user2803053

+0

私はそれを働かせました。助けてくれてありがとう – user2803053

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に設定されている場合、調達するNoMethodError防ぎます。 See this for more info about delegation

ここにコメントしてください。

+0

私は手順に従いますが、同じ問題を抱えています。それはすべての属性を返し、それはあなたがどちらを試しました – user2803053

+0

各メールを返さない?前者ですか?それはうまくいったはずです。注意深く見て、何かが欠けていないことを確認してください。私は助けるためにここにいる – illusionist

+0

私は助けてくれてありがとう。委任ヘルプのリンクが私に正しい答え – user2803053