I'm currently developing a memo app. A list of all the memos is displayed, but somehow I want to display a list of only the memos of the logged-in user on the memo list page.
This time we will learn about it.
First, add a column called user_id to the notes table (post-type table) to determine who made each post.
class CreateNotes < ActiveRecord::Migration[5.2]
def change
create_table :notes do |t|
t.text :title
t.integer :user_id
t.integer :category_id
t.text :explanation
t.timestamps
end
end
end
$ rails db:migrate:reset
When you save the post, put the information in the user_id column you added earlier. About build method
notes.controller.rb
def create
@note = current_user.notes.build(note_params)
@note.save
redirect_to notes_path
end
<div class='container'>
<div class='row'>
<h2>Memo list</h2>
<table class='table'>
<thead>
<tr>
<th>title</th>
<th>Category</th>
</tr>
</thead>
<tbody>
<% @notes.each do |note| %>
<% if user_signed_in? && current_user.id == note.user_id %> #Add here
<tr>
<td>
<%= link_to note_path(note) do %>
<%= note.title %>
<% end %>
</td>
<td><%= note.category.name %></td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
</div>
</div>
Described in each statement (repetition) of the memo list.
<% if user_signed_in? && current_user.id == note.user_id %>
Is the user logged in with this description? And check if the id of the logged-in user and the id of the user who posted the memo are the same.
If true, it will be displayed! I think this is okay!
I think the explanation is difficult to understand, but I hope it will be helpful. Also, if there are any mistakes, I would appreciate it if you could teach me.
Recommended Posts