2015-06-18 49 views
1

我正嘗試使用Sinatra構建電子商務網站,作爲練習。我很難看到如何實施「添加到購物車」按鈕。我想過這個問題的過程是:在sinatra中通過html按鈕調用Ruby方法

  1. 用戶點擊「添加到購物車」
  2. 按鈕「添加到購物車」調用一個紅寶石方法,例如點擊以下按鈕

    <input class='btn btn-primary' type='button' value='Add To Cart'></input> 
    

應該調用等

shop.add_to_cart(product, quantity) 

一種examp紅寶石方法這個方法可能看起來像什麼:

class Shop 
     attr_reader :cart 

     def initialize 
     @cart = [] 
     end 

     def add_to_cart(product, quantity) 
     @cart << product, quantity 
     end 
    end 

在Rails中,我認爲我們在控制器中使用helper_method? Sinatra有什麼類似的我可以做的嗎?

謝謝!

回答

4

注意:

這是如果你想在紅寶石做它。您可能也可以在javascript中做到這一點,正如其他答案中提到的,但我無法幫助您,因爲我不太瞭解JavaScript。


要在按鈕上運行ruby方法,首先需要創建僅有按鈕的<form>,然後在應用程序文件中運行一個路徑,該路徑將運行該方法,然後重定向回到您所在的頁面。這裏是我的代碼(沒有測試):

home.erb:

<form method="post" action="/runMethod"> 
    <input type="hidden" name="product" value="whatever"> 
    <input type="hidden" name="quantity" value="whatever"> 
    <input class='btn btn-primary' type='submit' value='Add To Cart'> 
</form> 

你會設置的兩個隱藏輸入值(其中我寫的「什麼」)的數量和產品根據他們的名字。

app文件:

class Shop 
    attr_reader :cart 

    def initialize 
    @cart = [] 
    end 

    def add_to_cart(product, quantity) 
    @cart << product, quantity 
    end 
end 
get '/' do 
    erb :home 
end 
post '/runMethod' do 
    shop.add_to_cart(params[:product], params[:quantity]) 
    redirect '/' 
end 
+0

謝謝!這正是我最終做的:) – zshnr

-2

Rails/Sinatra運行在服務器端。如果你想直接在Rails中發生,你可能需要一個表單並回傳數據。 時下人們使用JavaScript,它的JavaScript使得這種事情以異步方式進行回調。

1

這也與AJAX來完成,這樣您不必離開頁面:

$("#hideCarousel").submit(function() { 
     //posts the contents of the form to /action using ajax 
     $.post("/action", $("#myform").serialize(), function(result){ 
     // assuming result is a string of the updated data in html 
     // and assuming that your data goes in an element with the id data-table 
     $("#data-table").html(result) 
     }); 
     return false; // prevents the form from submitting normally 
    });