zshnr zshnr - 6 months ago 61
Ruby Question

Calling a Ruby Method via a html button in sinatra

I'm trying to build an e-commerce site using Sinatra, as practice. I'm getting stumped on how to implement the 'Add to Cart' Button. My thought process about it is:


  1. User clicks 'add to cart'

  2. The button 'add to cart' invokes a ruby method, for example clicking on the following button

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



should call a ruby method like

shop.add_to_cart(product, quantity)


An example of what this method might looking like:

class Shop
attr_reader :cart

def initialize
@cart = []
end

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


In Rails, I think we use the helper_method in the controller? Is there anything similar I can do in Sinatra?

Thanks!

Answer

Note:

This is if you want to do it in ruby. You could probably also do it in javascript as mentioned in the other answer, but I cannot help you with that because I don't know javascript well enough.


To run the ruby method on button click you first need to create a <form> with only the button, then have that run a route in your app file that will run the method then redirect back to the page you were on. Here is my code (have not tested):

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>

You would set the values of the two hidden inputs (where I wrote "whatever") to the quantity and product according to their names.

App File:

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
Comments