javascript - Rails: Using JQuery for post request instead of link_to -


right now, there "votes" model in rails app. each post on page has upvote button, written as:

<%= link_to "✓", votes_path(:vote => {:post_id => post.id, :up => false}), :method => :post %> 

where post_id post vote linked , boolean saying vote true. i'm trying use jquery instead of link_to page doesn't reload every time votes. however, don't understand ajax post request looks interface database model.

edit: votes controller:

def create     respond_to |format|         format.html         format.js { flash[:notice] = "vote created"} # , render <action>.js file}     end     @vote = vote.where(:post_id => params[:vote][:post_id], :user_id => current_user.id).first     if @vote         @vote.up = params[:vote][:up]         @vote.save     else         @vote = current_user.votes.create(vote_params)     end      redirect_to :back end 

use remote: true option ajax call.

<%= link_to "✓", votes_path(:vote => {:post_id => post.id, :up => false}, :format => :js), :method => :post, remote: true %> 

it generate ajax call controller. can manipulate action correspondingly.

respond_to |format|  format.html  format.js { flash[:notice] = "vote created"} # , render <action>.js file end 

update

def create     @vote = vote.where(:post_id => params[:vote][:post_id], :user_id => current_user.id).first     if @vote         @vote.up = params[:vote][:up]         @vote.save     else         @vote = current_user.votes.create(vote_params)     end      respond_to |format|         format.html         format.js { flash[:notice] = "vote created"} # , render <action>.js file}     end end 

it should work, let me know

and check this..

your app/assets/javascripts/application.js should contain.

//= require jquery  //= require jquery_ujs 

and erb should contain

<%= javascript_include_tag "jquery", "jquery_ujs" %>


Comments

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -