2016-01-06 53 views
0

我试图显示一个电话号码,当客户联系有它如何通过关联显示价值?

表:

|customers| 
    |id| |name| 
    1 Zidane 
    2 Mourinho 
    3 Guardiola 
    4 Ferguson 

|contacts| 
    |id| |customer_id| |name|   |phone| 
    1   1  Muller  
    2   1  Alaba   9872147 
    3   2  Aubameyang  2323234 
    4   3  Dante 
    5   3  Robben  
    6   3  Lewandoski  2343256 
    7   4  Ribery 

控制器:

def index 
    @customers = Customer.all 
end 

型号:

class Customer < ActiveRecord::Base 
    has_many :contacts 
end 

class Contact < ActiveRecord::Base 
    belongs_to :customer 
end 

查看:

<% @customers.each do |customer| %> 
    <%= customer.name %> 
    <% customer.contacts(:conditions=>['phone>0']).each do |contact| %> 
    <%= contact.name %> 
    <%= contact.phone %> 
    <% end %> 
<% end %> 

也试过:

<% @customers.each do |customer| %> 
    <%= customer.name %> 
    <% customer.contacts.each do |contact| %> 
    <%= contact.name %> 
    <%= contact.phone(:all,:conditions=>['phone>0']). %> 
    <% end %> 
<% end %> 

也试过,但只获得了第一次接触:

<%= customer.contacts.first(1).map { |c| c.phone } %> 

也试过,但只获得了最后的接触:

<%= customer.contacts.last(1).map { |c| c.phone } %> 

我想要这样的结果:

|customer| |name_contact| |phone| 
Zidane  Alaba   9872147 
CR7   Aubameyang 2323234 
Guardiola  Lewandoski 2343256 
Ferguson  Ribery 

回答

1

类似下面可以工作

<% customer.contacts.all {|c| c.phone.present?}.each do |contact| %> 

全段

<% @customers.each do |customer| %> 
    <%= customer.name %> 
    <% customer.contacts.all {|c| c.phone.present?}.each do |contact| %> 
    <%= contact.name %> 
    <%= contact.phone %> 
    <% end %> 
<% end %> 
+0

你在哪里展示contact.phone? –

+0

我假设代码的其余部分将保持不变,我只是建议更改为迭代器部分 –

+0

是不工作,没有显示任何东西 –