belongs_to has_many search information in the table

0

I have 2 tables: user and contact , and I created a third one for linking the two: user_contact :

class User < ActiveRecord::Base
    has_many:user_contacts
end
    class Contact < ActiveRecord::Base
    has_many:user_contacts
end
class UserPaciente < ActiveRecord::Base
    belongs_to:user
    belongs_to:paciente
end

I have this controller :

  def index
        @contacts = UserContact.where(:user_id => current_user.id)
  end

And this view :

  <tbody>
        <% @contacts.each do |contact| %>

  <tr>
    <td><%= contact.contact.id %></td>

  </tr>
<% end %>

I have tried everything, but it does not work, how can I get the list of contacts of current_user ?

    
asked by anonymous 09.08.2014 / 20:08

1 answer

2

Try using has_many through :

class User
  has_many :contacts, through :user_contact
end

class Contact
  has_many :users, through :user_contact
end

class UserContact
  belongs_to :user
  belongs_to :contact
end

contacts_controller :

def index
  @contacts = current_user.contacts
end

Do not forget to read the association session in the official guide .

    
09.08.2014 / 23:29