sho-muramatsu
@sho-muramatsu

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

一覧ページでいいねした企業をマイページで「いいね済み」で表示させたい

解決したいこと

RailsでインスタのようなWebアプリをつくっています。
一覧ページでいいねした企業をマイページで「いいね済み」で表示させたいです。

発生している問題・エラー

一覧ページでいいねした企業をマイページで表示はできますが、ボタンは未いいねのままです

【一覧ページでいいねした】
スクリーンショット 2021-12-23 13.53.25.jpg
【学生マイページにいくと「未いいね」で企業が表示される】
スクリーンショット 2021-12-23 13.53.46.jpg

または、問題・エラーが起きている画像をここにドラッグアンドドロップ

該当するソースコード

<businesses_controller.rb>
class BusinessesController < ApplicationController
  before_action :move_to_index, except: [:index, :search]
  before_action :search_business, only: [:index, :search]


  def index
    @businesses = Business.all.order("created_at DESC")
  end

  def show
    @business = Business.find(params[:id])
    if business_signed_in?
      likes = Like.where(business_id: current_business.id).pluck(:student_id)  # ログイン中ユーザーのお気に入りのstudent_idカラムを取得
      @like_list = Student.find(likes)     # studentテーブルから、お気に入り登録済みのレコードを取得
    end
  end

  def search
    @results = @p.result
  end

  def checked
    item = Business.find(params[:business_id])
    render json: { business: item }
  end

  private
  def search_business
    @p = Business.ransack(params[:q])
  end

  def move_to_index
    unless student_signed_in? || business_signed_in?
      redirect_to action: :index
      flash[:alert] = "ログイン/新規登録をして下さい"
    end
  end
end

class LikebizsController < ApplicationController
  before_action :set_business
  before_action :authenticate_student!   # ログイン中のユーザーのみに許可(未ログインなら、ログイン画面へ移動)

  def create
    @likebiz = Likebiz.create(student_id: current_student.id, business_id: @business.id) #投稿者本人以外に限定するif文追加
  end

  def destroy
    @likebiz = Likebiz.find_by(student_id: current_student.id, business_id: @business.id)
    @likebiz.destroy
  end

  private
  def set_business
    @business = Business.find(params[:business_id])
  end
end
function like_biz() {
  const like_bizs = document.querySelectorAll(".like_biz");
  like_bizs.forEach(function (like_biz) {
    //addEventListenerが重複して追加されることを回避
    if (like_biz.getAttribute("data-load") != null) {
      return null;
    }
    like_biz.setAttribute("data-load", "true");
    like_biz.addEventListener("click", () => {
      const LikeBizId = like_biz.getAttribute("data-id");
      const XHR = new XMLHttpRequest();
      XHR.open("GET", `/businesses/${LikeBizId}/checked`, true);
      XHR.responseType = "json";
      XHR.send();
      XHR.onload = () => {
        if (XHR.status != 200) {
          alert(`Error ${XHR.status}: ${XHR.statusText}`);
          return null;
        }
        const unlike_biz = document.getElementById(`unlike_biz_${LikeBizId}`);
        like_biz.removeAttribute("style", "display:block;");
        like_biz.setAttribute("class", "like_biz hidden");
        unlike_biz.setAttribute("style", "display:block");
      };
    });
  });
}
setInterval(like_biz, 1000);
function unlike_biz() {
  const unlike_bizs = document.querySelectorAll(".unlike_biz");
  unlike_bizs.forEach(function (unlike_biz) {
    //addEventListenerが重複して追加されることを回避
    if (unlike_biz.getAttribute("data-load") != null) {
      return null;
    }
    unlike_biz.setAttribute("data-load", "true");
    unlike_biz.addEventListener("click", () => {
      const UnLikeBizId = unlike_biz.getAttribute("data-id");
      const XHR = new XMLHttpRequest();
      XHR.open("GET", `/businesses/${UnLikeBizId}/checked`, true);
      XHR.responseType = "json";
      XHR.send();
      XHR.onload = () => {
        if (XHR.status != 200) {
          alert(`Error ${XHR.status}: ${XHR.statusText}`);
          return null;
        }
        const like_bizs = document.getElementById(`like_biz_${UnLikeBizId}`);
        unlike_biz.removeAttribute("style", "display:block;");
        like_bizs.setAttribute("style", "display:block");
      };
    });
  });
}
setInterval(unlike_biz, 1000);
<% if business.image.attached? %>
  <%= image_tag business.image.variant(resize: '500x500'), class: 'index-image'%>
<% else %>
  <%= image_tag "default_icon.png", class: "index-image" %>
<% end %>
<%= link_to '詳細', business_path(business.id) %>
<% if student_signed_in? %>
  <div class="unlike_biz" id="unlike_biz_<%= business.id %>" data-id=<%= business.id %> >
    <%= link_to business_likebizs_path(business.id), method: :delete, remote: true do %>
      <%= image_tag "favorited.png", class:"favorite_image_switch"%>
    <% end %>
  </div>
  <div class="like_biz" id="like_biz_<%= business.id %>" data-id=<%= business.id %> >
    <%= link_to business_likebizs_path(business.id), method: :post, remote: true do %>
      <%= image_tag "favorite.png", class:"favorite_image_switch"%>
    <% end %>
  </div>
<% end %>
<p class="student_content">会社名:<%= business.corp_name %></p>
<p class="student_content">一言:<%= business.staff_msg %></p>
<div class="padding-block"></div>
<div class="page-heading">
  <p>企業一覧ページ</p><%= link_to '学生一覧へ', students_path %>
  <p class="text-alert" id="alert"><%= alert %></p>
</div>

<div class="search-form">
  <%= search_form_for @p, url: search_businesses_path do |f| %>
    <%= f.label :feature_id_eq, '特徴' %>
    <%= f.collection_select :feature_id_eq, Feature.all, :id, :name, include_blank: '指定なし' %>
    <%= f.label :industry_id_eq, '業界' %>
    <%= f.collection_select :industry_id_eq, Industry.all, :id, :name, include_blank: '指定なし' %>
    <%= f.submit '検索' %>
  <% end %>
</div>

<div class="contents row">
  <% @businesses.each do |business| %>
    <%= render "bizlist", business: business %>
  <% end %>
</div>

<% if student_signed_in? %>
  <% if current_student.id == @student.id %>
    <p>お気に入り企業</p>
    <% if @likebiz_list.present? %>
      <% @likebiz_list.each do |business| %>
        <%= render "/businesses/bizlist", business: business %>
      <% end %>
    <% else %>
      <p>まだお気に入りの企業はいません</p>
    <% end %>
  <% end %>
<% end %>

自分で試したこと

・viweでこのようにif文で条件分岐させたがjsが邪魔しているのかうまく作動しなかった

_bizlist.html

<% if student_signed_in? %>
  <% if Likebiz.find_by(student_id: current_student.id).nil? %>
    <div class="like_biz" id="like_biz_<%= business.id %>" data-id=<%= business.id %> >
      <%= link_to business_likebizs_path(business.id), method: :post, remote: true do %>
        <%= image_tag "favorite.png", class:"favorite_image_switch"%>
      <% end %>
    </div>
  <% else %>
    <div class="unlike_biz" id="unlike_biz_<%= business.id %>" data-id=<%= business.id %> >
      <%= link_to business_likebizs_path(business.id), method: :delete, remote: true do %>
        <%= image_tag "favorited.png", class:"favorite_image_switch"%>
      <% end %>
    </div>
  <% end %>
<% end %>
0

No Answers yet.

Your answer might help someone💌