Reputation: 13
I want to show to all users who like "Term", how do I do it?
And this is what I did.
likes_controller.rb
def index
@likes = Like.all
end
index.html.erb (like)
<table class="table">
<thead class="thead-dark">
<tr>
<th scope="col">STT</th>
<th scope="col">UserName</th>
</tr>
</thead>
<tbody>
<% @likes.each do |like| %>
<tr>
<th scope="row"><%= @like.id %></th>
<td></strong><%= @like.user.username %></strong>></td>
<tr>
<% end %>
</tbody>
</table>
like.rb
id, term_id, user_id
routes
resources :terms do
resources :likes
end
term
belong_to :user
has_many :likes
user :
has_many :likes
has_many :terms
like :
belong_to :user
belong_to :term
I'm not sure if I have provided enough documents, if not, please leave me a comment
Upvotes: 0
Views: 51
Reputation: 12203
It's hard to be precise with this without you updating the question to show the relationships setup in the three models, but you could do something like:
#term.rb
has_many :users, through: :likes
That'll give you access to term.users
directly, returning all those that have liked the term.
You could then load the term in your controller (be sure to eager load the users):
def index
@term = Term.find(params[:id]).includes(:users)
end
And then in the view:
<% @term.users.each do |user| %>
<tr>
<td scope="row"><%= user.like_id %></td>
<td><strong><%= user.username %></strong>></td>
<tr>
<% end %>
Please note I've switched to use two td
tags in the loop - the th
tag should be used for the header row.
Hope that helps - let me know how you get on or if you have any questions :)
Upvotes: 2
Reputation: 6455
Try:
# likes_controller.rb
def index
@term = Term.find(params[:id]
@likes = @term.likes
end
## likes/index.html.erb
<% @likes.each do |like| %>
<tr>
<th scope="row"><%= @like.id %></th>
<td></strong><%= @like.user.username %></strong>></td>
</tr>
<% end %>
Upvotes: 0