2016-04-03 58 views
0

我有兩個模型類叫做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 
+0

爲什麼在模型中都有'belongs_to'關聯。因爲它看起來應該是Customer'has_many'命令。不是嗎? – dp7

+0

@dkp我忘了將它添加到我的模型,但我回去改變它。 – user2803053

+0

您已將它添加到'Order'模式中,而應將其添加到'Customer'模型中,像這樣'has_many:orders' – dp7

回答

0

這將返回的電子郵件ID一個接一個其他 -

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

當我運行上面的代碼時,它會返回所有屬性,如名稱,電子郵件和電話號碼。此外,它不會一個接一個地返回電子郵件ID。它將返回表格每個插槽中的所有電子郵件。 – 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,防止被提出的一個NoMethodErrorSee this for more info about delegation

評論這裏,如果需要進一步的援助。

+0

我遵循的步驟,但我遇到了同樣的問題。它返回所有的屬性,它不會返回每個電子郵件 – user2803053

+0

你試過哪一個?前者還是後者?它應該工作。請仔細查看並確保不會丟失任何東西。我在這裏幫助 – illusionist

+0

我得到它的工作感謝您的幫助。代表團的鏈接幫助我指出正確的答案 – user2803053

相關問題