Implementieren Sie eine Lesezeichenfunktion (Favoritenregistrierung, wie) für Beiträge.
ruby 2.5.7 Rails 5.2.4.3 OS: macOS Catalina
Terminal
$ rails g model Bookmark user:references post:references
Fügen Sie null: false hinzu, um einen leeren Speicher in der Datenbank zu verhindern.
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
Zu jedem Modell hinzugefügt.
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 "Bearbeiten", edit_post_path(@post) %></td>
<% if @post.bookmarked_by?(current_user) %>
<td><%= link_to "Lesezeichen entfernen", post_bookmarks_path(@post), method: :delete %></td>
<% else %>
<td><%= link_to "Lesezeichen", post_bookmarks_path(@post), method: :post %></td>
<% end %>
</tr>
</tbody>
Beschreiben Sie im Controller den Ort, den Sie anzeigen möchten. Dieses Mal wird es in app / views / home / mypage.html.erb angezeigt.
erb:app/views/homes/mypage.html.erb
<table>
<caption>Lesezeichenliste</caption>
<thead>
<tr>
<th>Gepostet mit Namen</th>
<th>Titel</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