zshnr
zshnr

Reputation: 279

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!

Upvotes: 1

Views: 6051

Answers (3)

mgabz
mgabz

Reputation: 733

This can also be accomplished with ajax so that you dont have to leave the page:

    $("#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
    });

Upvotes: 2

thesecretmaster
thesecretmaster

Reputation: 1984

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

Upvotes: 4

Mircea
Mircea

Reputation: 10566

Rails/Sinatra run on the server side. If you want stuff happening in Rails directly you probably need a form and post back data. nowadays people use javascript and it's javascript that makes the callbacks in an asynchronous fashion for this kinds of things.

Upvotes: -2

Related Questions