0

I'm trying to rewrite the following button code so that instead of redirecting me to the show page, it just creates the object and the current page stays displayed.

<div class="colors">
    <li class="colors" id="greys">
        <%= button_to "some text", votes_path(color: 'grey', kid_id: current_kid, scoop_id: scoop.id, :method => :create), class: 'grey color-button' %>
    </li>
</div>
Arslan Ali
  • 17,418
  • 8
  • 58
  • 76
justin
  • 57
  • 4

2 Answers2

3

You should use a remote flag to send the request via javascript. And possibly give feedback to the user.

To send a request via js in rails you have to add remote: true to the options hash:

<div class="colors">
    <li class="colors" id="greys">
        <%= button_to "some text", votes_path(color: 'grey', kid_id: current_kid, scoop_id: scoop.id, :method => :create), class: 'grey color-button', remote: true %>
    </li>
</div>

In your controller you can do special responses by respondig to js

#votes controller
def create
  # ...
  respond_to do |format|
    format.js render
  end
end

In your create.js.erb you can write javascript code with embeded ruby to give responses. You can even render partials here.

alert('create.js.erb')
joseramonc
  • 1,811
  • 2
  • 21
  • 40
0

First, have some id for your button:

<%= button_to "some text", votes_path(color: 'grey', kid_id: current_kid, scoop_id: scoop.id, :method => :create), class: 'grey color-button' id: 'buttonID' %>

And then, in your Javascript code, whenever the button is clicked, send a request to server, create the new record, and then update the current page, so that it shows the record has been created.

I would show you the sculpture of how to do it:

$("buttonID").click(function() {
    $.ajax({
        url: "some_url" // Your URL, for example, /votes
        type: "POST", // The type of request
        data: { color: "grey" } // Send data to server in this format
        success: function() {
            // Here you can update the page so that the user could
            // know the data has been posted, and no need to press 
            // the button again
        } 
    });
});
Arslan Ali
  • 17,418
  • 8
  • 58
  • 76