2016-04-03 57 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

相关问题