我对此很陌生,我正在尝试做一些非常简单的事情,但我不知道从哪里开始。如果选择了单选按钮,我只需将新发布的链接的“投票”计数从 0 增加到 10。这是我到目前为止的完整代码,任何帮助将不胜感激:
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!
get '/' do
@links = Link.all :order => :id.desc
haml :index
end
get '/hot' do
@links = Link.all_sorted_desc
haml :index
end
get '/:id' do
@link = Link.get params[:id]
haml :index
end
post '/' do
l = Link.new
l.title = params[:title]
l.url = params[:url]
l.bullet = params[:bullet]
l.created_at = Time.now
l.save
redirect back
end
put '/:id/vote/:type' do
l = Link.get params[:id]
l.points += params[:type].to_i
l.save
redirect back
end
delete '/:id' do
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 do |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"}