Sinatra/Ruby new to programming - increasing an integer if a radio button is selected -
i new , trying pretty simple not sure begin. need increase "vote" count of newly posted link 0 10 if radio button selected. here complete code have far, appreciated:
require 'sinatra' require 'data_mapper' require 'haml' require 'sinatra/reloader' set :bind, '0.0.0.0' datamapper::setup(:default,"sqlite3://#{dir.pwd}/example.db") class link include datamapper::resource property :id, serial property :title, string property :url, text property :bullet, boolean, :default => false property :score, integer property :points, integer, :default => 0 property :created_at, time attr_accessor :score def calculate_score time_elapsed = (time.now - self.created_at) / 3600 self.score = ((self.points-1) / (time_elapsed+2)**1.8).real end def self.all_sorted_desc self.all.each { |item| item.calculate_score }.sort { |a,b| a.score <=> b.score}.reverse end end datamapper.finalize.auto_upgrade! '/' @links = link.all :order => :id.desc haml :index end '/hot' @links = link.all_sorted_desc haml :index end '/:id' @link = link.get params[:id] haml :index end post '/' l = link.new l.title = params[:title] l.url = params[:url] l.bullet = params[:bullet] l.created_at = time.now l.save redirect end put '/:id/vote/:type' l = link.get params[:id] l.points += params[:type].to_i l.save redirect end delete '/:id' l = link.get params[:id] l.destroy redirect '/' end __end__ @@ layout %html %head %link(rel="stylesheet" href="/css/bootstrap.css") %link(rel="stylesheet" href="/css/style.css") %body .container #main .title learn sinatra .options %a{:href => ('/')} new | %a{:href => ('/hot')} hot = yield @@ index #links-list -@links.each |l| .row .span3 %span.span %form{:action => "#{l.id}/vote/1", :method => "post"} %input{:type => "hidden", :name => "_method", :value => "put"} %input{:type => "submit", :value => "u"} %span.points #{l.points} %span.span %form{:action => "#{l.id}/vote/-1", :method => "post"} %input{:type => "hidden", :name => "_method", :value=> "put"} %input{:type => "submit", :value => "d"} .span6 %span.link-title %h3 %a{:href => (l.url)} #{l.title} %span.span %form{:action => "#{l.id}", :method => "post"} %input{:type => "hidden", :name => "_method", :value=> "delete"} %input{:type => "submit", :value => "x"} #add-link %form{:action => "/", :method => "post"} %input{:type => "text", :name => "title", :placeholder => "title"} %input{:type => "text", :name => "url", :placeholder => "url"} %input{:type => "radio", :name => "bullet", :value => "10"} %input{:type => "submit", :value => "submit"}
you have define route function receives get/post request should trigger column update adds 1 vote count
Comments
Post a Comment