belongs_to has_many search information in table

Asked

Viewed 173 times

0

I have 2 tables: user and contact, and created a third to connect 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’ve tried everything, but it doesn’t work, how can I find the list of contacts of current_user?

  • "I have 3 tables" but you speak of 2... (?) and "does not work" is not an adequate description... what happens? You can [Edit] ask to add more details.

  • I’ve already edited, I hope to be more explicit

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

Don’t forget to read the session of associations in the official guide.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.