1
我遇到麻烦更新像a /不像(我称之为时钟/ unclock)按钮与ajax。我不确定如何为它实现js,以及如果我需要更改我目前使用的部分来形成partials。任何人都可以通过某种方式来调整我的当前代码以实现这一目标吗?Rails Ajax喜欢/不像按钮
(用户可钟和应用unclock产品)
谢谢!
的application.js
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require masonry/jquery.masonry
//= require_tree .
的routes.rb
resources :products do
resources :clocks
end
end
products.controller.rb
def show
@product = Product.find_by!(slug: params[:id])
@clockers = @product.clockers
@categories = @product.categories
if current_user
@current_clock = current_user.clocks.find_by(product_id: @product.id)
end
end
clocks.controller.rb
class ClocksController < ApplicationController
before_action :require_signin
before_action :set_product
respond_to :html, :js
def create
@product.clocks.create!(user: current_user)
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
def destroy
clock = current_user.clocks.find(params[:id])
clock.destroy
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
private
def set_product
@product = Product.find_by!(slug: params[:product_id])
end
end
product.rb
has_many :clocks, dependent: :destroy
has_many :clockers, through: :clocks, source: :user
show.html.erb(产品外形,我想AJAX工作)
<div id="show_clock">
<% if current_user %>
<% if @current_clock %>
<%= render 'products/unclock' %>
<% else %>
<%= render 'products/clock' %>
<% end %>
<% end %>
</div>
_unclock.html.erb
<%= button_to product_clock_path(@product, @current_clock), method: :delete, remote: true do %>
<i class="glyphicon glyphicon-time" style= "color:red;"> </i>
<% end %>
_clock.html .erb
<%= button_to product_clocks_path(@product), remote: true do %>
<i class="glyphicon glyphicon-time" style= "color:white;"> </i>
<% end %>