Sebastian Zeki
Sebastian Zeki

Reputation: 6874

how to show details of current user from a related table in rails

I have a simple 1 user to many relationships database structure.

enter image description here

On my page I am able to use <%= current_user.about %> to get the about field for a current user. I would like to get the fields called followed_id and follower_id also for the current user (there may be many). Is there an easy way to do this on the page without calling the controller given there is only one current user?

Upvotes: 2

Views: 219

Answers (1)

omnikron
omnikron

Reputation: 2321

You could do something like:

<% current_user.relationships.pluck(:followed_id, :follower_id).each do |followed_id, follower_id|
  <%= # do some stuff with your followed_id and follower_id variables %>
<% end %>

(the pluck is just so that you only make a single call to your database, instead of one for each relationship - but there are other ways of doing this.)


If you can I would strongly consider renaming the relationships table, because that is really a very confusing name for a relational database. It's like having a table called table with columns called column, row, and select.

Upvotes: 2

Related Questions