現在, Rails 5.1.6でフリーマーケットアプリを作成しております.アプリ内でいいね機能を実装しているのですが,いいねボタンを押す(submitをする)と,当然ながらページの最上部に遷移してしまいます. これをどうにかスクロール位置を保持することができないか模索しているのですが,うまくいきません.どなたか解決策を教えていただけませんでしょうか.
以下,関係のあるコードを添付しておきます.
_micropost.html.erb(マイクロポストのパーシャル)
<li id="micropost-<%= micropost.id %>" class="col-sm-4 micropost_whole_style"> <h2 class="micropost_title_style"><%= link_to micropost.title, micropost %></h2> <p class="micropost_price_style"><%= micropost.price %></p> <span class=" micropost_timestamp_style"> Posted <%= time_ago_in_words(micropost.updated_at) %> ago. </span> <div> <% if current_user.favorited?(micropost) %> <%= render 'favorites/unfavorited', micropost: micropost %> <% else %> <%= render 'favorites/favorite', micropost: micropost %> <% end %> </div> </li>
_favorite.html.erb(いいねボタン(いいねする用))
<%= form_with(model: Favorite.new, url: favorites_path(micropost_id: micropost.id), method: :post) do |f| %> <%= button_tag(type: "submit") do %> <i class="far fa-heart"></i><span id="favorite_count"><%= micropost.favorites.count %></span> <% end %> <% end %>
_unfavorited.html.erb(いいねボタン(いいねを解除する用))
<%= form_with(model: Favorite.new, url: favorite_path(Favorite.find_by(user_id: current_user.id, micropost_id: micropost.id)), method: :delete) do |f| %> <%= button_tag(type: "submit") do %> <i class="fas fa-heart favorited"></i><span id="favorite_count"><%= micropost.favorites.count %></span> <% end %> <% end %>
favorites_controller.rb(Favoritesコントローラ)
class FavoritesController < ApplicationController before_action :logged_in_user def create Favorite.create!(user_id: current_user.id, micropost_id: params[:micropost_id]) # respond_to do |format| # format.html { redirect_to request.referrer || root_url } # format.js # end redirect_to request.referrer || root_url end def destroy @favorite = Favorite.find(params[:id]) @favorite.destroy # respond_to do |format| # format.html { redirect_to request.referrer || root_url } # format.js # end redirect_to request.referrer || root_url end end
よろしくお願いします.
あなたの回答
tips
プレビュー