2014-11-25 82 views
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 %> 

回答