Implement bookmark (favorite registration, like) function for posts.
ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
-Build login environment with devise -Posting function that only logged-in users can do -Post editing function (update, delete)
Terminal
$ rails g model Bookmark user:references post:references
Add null: false to prevent empty storage in the database.
db/migate/xxxxxxxxxxxxxx_create_bookmarks.rb
class CreateBookmarks < ActiveRecord::Migration[5.2]
def change
create_table :bookmarks do |t|
t.references :user, foreign_key: true, null: false
t.references :post, foreign_key: true, null: false
t.timestamps
end
end
end
Terminal
$ rails db:migrate
Added to each model.
app/models/bookmark.rb
validates :user_id, uniqueness: { scope: :post_id }
app/models/post.rb
has_many :bookmarks, dependent: :destroy
def bookmarked_by?(user)
bookmarks.where(user_id: user).exists?
end
app/models/user.rb
has_many :bookmarks, dependent: :destroy
Terminal
$ rails g controller bookmarks
app/controllers/bookmarks_controller.rb
class BookmarksController < ApplicationController
before_action :authenticate_user!
def create
@post = Post.find(params[:post_id])
bookmark = @post.bookmarks.new(user_id: current_user.id)
if bookmark.save
redirect_to request.referer
else
redirect_to request.referer
end
end
def destroy
@post = Post.find(params[:post_id])
bookmark = @post.bookmarks.find_by(user_id: current_user.id)
if bookmark.present?
bookmark.destroy
redirect_to request.referer
else
redirect_to request.referer
end
end
end
config/routes.rb
resources :posts, except: [:index] do
resource :bookmarks, only: [:create, :destroy]
end
erb:app/views/posts/show.html.erb
<tbody>
<tr>
<td><%= @post.user.name %></td>
<td><%= @post.title %></td>
<td><%= @post.body %></td>
<td><%= link_to "Edit", edit_post_path(@post) %></td>
<% if @post.bookmarked_by?(current_user) %>
<td><%= link_to "Unbookmark", post_bookmarks_path(@post), method: :delete %></td>
<% else %>
<td><%= link_to "Bookmark", post_bookmarks_path(@post), method: :post %></td>
<% end %>
</tr>
</tbody>
Describe the following in the controller of the place you want to display. This time, it will be displayed in app / views / homes / mypage.html.erb.
erb:app/views/homes/mypage.html.erb
<table>
<caption>Bookmark list</caption>
<thead>
<tr>
<th>Posted by name</th>
<th>title</th>
<th>Text</th>
</tr>
</thead>
<tbody>
<% @bookmarks.each do |bookmark| %>
<tr>
<td><%= bookmark.post.user.name %></td>
<td>
<%= link_to post_path(bookmark.post) do %>
<%= bookmark.post.title %>
<% end %>
</td>
<td><%= bookmark.post.body %></td>
</tr>
<% end %>
</tbody>
</table>
app/controllers/homes_controller.rb
def mypage
@bookmarks = Bookmark.where(user_id: current_user.id)
end
Recommended Posts