0
0

More than 3 years have passed since last update.

非同期いいね

Posted at
osotmy.rb
class Ostomy < ApplicationRecord
 has_many :favorites, dependent: :destroy

def favorited_by?(staff)
  favorites.where(staff_id: staff.id).exists?
end
fovorite.rb
class Favorite < ApplicationRecord
  belongs_to :staff
  belongs_to :ostomy
end
staff.rb
class Staff < ApplicationRecord
  has_many :favorites
end
fovorite.contoroller
class Staff::FavoritesController < ApplicationController
   #医療staffが患者さん記録にいいねつける
   before_action :authenticate_staff!
  def create
    @ostomy = Ostomy.find(params[:ostomy_id])
    favorite = @ostomy.favorites.new(staff_id: current_staff.id)
    favorite.save
  end

  def destroy
    @ostomy = Ostomy.find(params[:ostomy_id])
    favorite = @ostomy.favorites.find_by(staff_id: current_staff.id)
    favorite.destroy
  end

  private
  def ostomy_params
      params.require(:ostomy).permit(:color,:edema,:skin,:h_size,:w_size,:comment,:image)
  end

end

/_fovorite.html.erb
<% if ostomy.favorited_by?(current_staff) %>
  <%= link_to staff_ostomy_favorites_path(ostomy), method: :delete,remote: true do%>
   <%= ostomy.favorites.count%>❤︎よいいね
  <%end%>
<% else %>
  <%= link_to staff_ostomy_favorites_path(ostomy), method: :post,remote: true do %>
   <%= ostomy.favorites.count%>♡︎いいね
  <%end%>
<% end %>
staff/ostomy/show.html.erb
<div class="favorite"><%= render 'staff/favorites/favorite',ostomy: @ostomy %></div>
create.js.erbとdestroy.js.erb
$(".favorite").html("<%= j(render'staff/favorites/favorite', ostomy: @ostomy) %>");
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0