Reputation: 1149
I'm trying to show a phone number when customer contact has it
Table:
|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
Controller:
def index
@customers = Customer.all
end
Model:
class Customer < ActiveRecord::Base
has_many :contacts
end
class Contact < ActiveRecord::Base
belongs_to :customer
end
View:
<% @customers.each do |customer| %>
<%= customer.name %>
<% customer.contacts(:conditions=>['phone>0']).each do |contact| %>
<%= contact.name %>
<%= contact.phone %>
<% end %>
<% end %>
Also tried:
<% @customers.each do |customer| %>
<%= customer.name %>
<% customer.contacts.each do |contact| %>
<%= contact.name %>
<%= contact.phone(:all,:conditions=>['phone>0']). %>
<% end %>
<% end %>
Also tried but is only getting the first contact:
<%= customer.contacts.first(1).map { |c| c.phone } %>
Also tried but is only getting the last contact:
<%= customer.contacts.last(1).map { |c| c.phone } %>
I want this as result:
|customer| |name_contact| |phone|
Zidane Alaba 9872147
CR7 Aubameyang 2323234
Guardiola Lewandoski 2343256
Ferguson Ribery
Upvotes: 0
Views: 27
Reputation: 18762
Something like below can work
<% customer.contacts.all {|c| c.phone.present?}.each do |contact| %>
Full snippet
<% @customers.each do |customer| %>
<%= customer.name %>
<% customer.contacts.all {|c| c.phone.present?}.each do |contact| %>
<%= contact.name %>
<%= contact.phone %>
<% end %>
<% end %>
Upvotes: 1