christopherlovell
christopherlovell

Reputation: 4159

Increment integer model variable using ajax

Just starting to use rails and I hit a snag that I can't seem to find an accurate answer to for my specific case.

I wish to increment the variable 'votes' in my 'Font' model through ajax. I currently have Javascript that triggers this through a click action on a div

The nearest example I've found to my problem is a Favourite button i.e. twitter. However, most 'Favourite button' functionality uses a separate Favourite data model; I only wish to increment the variable therefore I see little point in designing a whole new data model for this.

The Javascript on index.html.erb

$("#heading_vote").click(function(){
  var fontid='<%= h @font_1.id %>'
  $(".text").html(fontid);
  $.ajax({type: "GET", url: 'fonts/'+fontid+'/vote', success: function(){
      $(".text").html('voted');
    }
  });
});

rake routes

 Prefix Verb   URI Pattern               Controller#Action
     root GET  /                         home#index
    fonts GET  /fonts(.:format)          fonts#index
         POST  /fonts(.:format)          fonts#create
 new_font GET  /fonts/new(.:format)      fonts#new
edit_font GET  /fonts/:id/edit(.:format) fonts#edit
     font GET  /fonts/:id(.:format)      fonts#show
        PATCH  /fonts/:id(.:format)      fonts#update
          PUT  /fonts/:id(.:format)      fonts#update
       DELETE  /fonts/:id(.:format)      fonts#destroy
         POST  /fonts/:id/vote(.:format) fonts#vote

font.rb model (sets the 'votes' variable to 0 as default when initialised)

class Font < ActiveRecord::Base  
  validates :title, presence: true, length: { minimum: 5 }
  validates :linktitle, presence: true, length: { minimum: 5 }
  validates :link, presence: true, length: { minimum: 5 }

  #set defauls value for votes variable
  before_save :default_values
  def default_values
    self.votes ||= '0'
  end
end

The action inside font_controller.rb that increments the 'votes' variable by one:

def vote
  @font = Font.find(params[:id])

  @font.update_attribute("votes",votes+1)    

  respond_to do |format|
    format.html
    format.js
  end
end

my routes.rb file (I think this is where the problem is - am I linking correctly to the vote action in the Font controller?):

app::Application.routes.draw do

  root to: "home#index" 

  resources :fonts

  post '/fonts/:id/vote' => 'fonts#vote'

Any help, or advice on debugging, would be appreciated. Thanks

Upvotes: 1

Views: 382

Answers (1)

rmagnum2002
rmagnum2002

Reputation: 11421

They way I would do:

I'd the remove js code then:

in routes file:

post '/fonts/:id/vote' => 'fonts#vote', as: :vote

in view template:

<%= link_to 'Vote', vote_path(@font), remote: true %>

in app/views/fonts/vote.js.erb

alert('Vote saved!');

you might want to write more js things into js.erb file to make it look more user friendly, but as a demo an alert will be fine.

Upvotes: 1

Related Questions