我想實現一個訂閱/取消訂閱切換按鈕,它會創建/銷燬訂閱objectonClick,但我很難找到一個優雅的解決方案。切換按鈕動作OnClick - JQuery + Rails
我已經嘗試過多種想法,並得出結論,我需要使用Javascript來實現這一點。但是,我不確定是否/如何在用戶單擊該按鈕時同時更改按鈕文本及其操作。請參閱下面的button_to 'Subscribe'
和button_to 'Unubscribe'
。
任何意見或建議將不勝感激!
藝術家索引視圖:
<% @artists.each do |artist| %>
<tr id="tr_<%=artist.id%>">
<td><%= artist.name %></td>
<td><%= artist.artist_data["name"] %></td>
<td><%= artist.artist_data["facebook_tour_dates_url"] %></td>
<td><%= artist.artist_data["mbid"] %></td>
<td><%= artist.artist_data["upcoming_event_count"] %></td>
<% if artist.is_not_subscribed?(user_id: @user.id, artist_id: artist.id)%>
<td><%= button_to 'Subscribe', user_subscriptions_path(@user, artist_id: artist.id), method: :post, id: "subscribe_link_#{artist.id}", class: "subscribe", remote: true %></td>
<% else %>
<td><%= button_to 'Unsubscribe', user_subscription_path(@user, artist.find_subscription(user_id: @user.id, artist_id: artist.id)), method: :delete, id: "unsubscribe_link_#{artist.id}", class: "unsubscribe", remote: true %></td>
<% end %>
<% end %>
訂閱控制器:
def create
@user = User.find(params[:user_id])
@subscription = @user.subscriptions.build(subscription_params)
@subscription.artist_id = params[:artist_id]
respond_to do |format|
if @subscription.save
format.html { redirect_to artists_path, notice: 'Subscription was successfully created.' }
format.json { render :show, status: :created, location: @subscription }
format.js
else
format.html { render :new }
format.json { render json: @subscription.errors, status: :unprocessable_entity }
format.js { render js: @subscription, notice:'Unable to create Subscription' }
end
end
end
def destroy
@subscription = Subscription.find(params[:id])
@subscription.destroy
respond_to do |format|
format.html { redirect_to user_subscriptions_url, notice: 'Subscription was successfully destroyed.' }
format.json { head :no_content }
format.js
end
end
訂閱模式:
class Subscription < ActiveRecord::Base
belongs_to :artist
belongs_to :user
accepts_nested_attributes_for :artist
end
藝術家型號:
class Artist < ActiveRecord::Base
include Subscribable
has_and_belongs_to_many :events
has_many :subscriptions
has_many :users, through: :subscriptions
validate :artist_already_exists?
end
用戶模型:
class User < ActiveRecord::Base
include Subscribable
has_many :subscriptions
has_many :artists, through: :subscriptions
accepts_nested_attributes_for :subscriptions
end