我正在尝试在客户联系时显示电话号码
表:
|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
答案 0 :(得分: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 %>