我已经在我的rails应用程序中实现了一个收藏夹系统,该系统可以在Tracks模型的各个显示页面上使用。这都是通过“收藏夹”控制器处理的,因此我试图对索引页面和显示页面使用相同的js文件。到目前为止,这是我尝试过的。如果我只有显示页面的材料,它会起作用,如果我这样做,那么javascript根本不会起作用。
favorite.js.erb
<% if current_page?(track_path(@track)) %>
$("#favorites").html("<%= escape_javascript(render('tracks/favorites')) %>");
<% else %>
$("#favorites").html("<%= escape_javascript(render('albums/favorites')) %>");
<% end %>
曲目/收藏夹的部分
<% if user_signed_in? && current_user.favorited?(@track) %>
<%= link_to image_tag('icons/heart_full.svg', width: 20), track_unfavorite_path(@track), method: :post, remote: true %>
<% else %>
<%= link_to image_tag('icons/heart_empty.svg', width: 20), track_favorite_path(@track), method: :post, remote: true %>
<% end %>
专辑/收藏夹的部分
<% if user_signed_in? && current_user.favorited?(track) %>
<%= link_to image_tag('icons/heart_full.svg', width: 20), track_unfavorite_path(track),
method: :post, remote: true %> <%= pluralize( track.favorites.count, 'favorite' ) %>
<% else %>
<%= link_to image_tag('icons/heart_empty.svg', width: 20), track_favorite_path(track),
method: :post, remote: true %> <%= pluralize( track.favorites.count, 'favorite' ) %>
<% end %>
将实例变量作为参数传递给show页面,但尝试为循环结果执行操作会使我感到困惑。
favorites_controller.rb
class FavoritesController < ApplicationController
before_action :authenticate_user!
before_action :find_track
def favorite
@track.favorites.where(user_id: current_user.id).first_or_create
respond_to do |format|
format.html { redirect_to @track }
format.js
end
end
def unfavorite
@track.favorites.where(user_id: current_user.id).destroy_all
respond_to do |format|
format.html { redirect_to @track }
format.js
end
end
private
def find_track
@track = Track.find(params[:track_id])
end
end
“曲目显示”页面的视图很简单:
<div id="favorites">
<%= render 'tracks/favorites' %>
</div>
索引页面上的循环视图:
<% @tracks.each do |track| %>
<div class="track_thumbnail">
<% if track.avatar? %>
<%= link_to image_tag(track.avatar.url), track_path(track), width: 100, title: track.title %>
<% else %>
<%= link_to image_tag(track.user.avatar.url), track_path(track), width: 100, title: track.title %>
<% end %>
<%= link_to track.user.username, user_path(track.user) %>
</div>
<div class="track_overview">
<h2><%= link_to track.title, track_path(track) %><% if track.explicit == "explicit" %> (explicit)<% end %></h2>
<p class="description"><%= truncate(track.description, length: 160) %></p>
<div class="icons_container">
<div id="favorites">
<%= render 'albums/favorites', :track => track %>
</div>
</div>
</div>
<% end %>