Ruby on Sinatra:表单数据的发送和接收

Posted by baicai on November 22, 2015

比如有一个添加app的功能,它的页面haml是这样的

!!! XML
%html
  %head
    %title PromoteAppManager
  %body{:bgcolor => "white"}
    %h1{:style => "font-family:Calibri,Arial,YaHei"} New
    %hr
    %form{:align => "center",:name => "input",:action => "/promoteapp/manager/new",:method => "post"}
      %table
        %tr
          %td AppId:
          %td
            %input{:type => "text",:name => "appid"}
        %tr
          %td Title:
          %td
            %input{:type => "text",:name => "title"}
        %tr
          %td Content:
          %td
            %input{:type => "text",:name => "content"}
        %tr
          %td Logo:
          %td
            %input{:type => "text",:name => "logo"}
        %tr
          %td Status:
          %td
            %input{:type => "text",:name => "_status"}
        %tr
          %td
          %td
            %input{:align => "left",:type => "submit",:value => "Submit"}
    %hr

当点击Submit按钮时候,通过form表单提交到/promoteapp/manager/new,指定post方式。

QQ截图20151123094542

路由接收处:

get '/promoteapp/manager/new' do
	haml :promoteappmanagernew
end

post '/promoteapp/manager/new' do
  postdata = URI.decode_www_form_component(request.body.read)
  params = URI.decode_www_form(postdata)
  model = PromoteApp.new
  model.appid = params.assoc("appid").last
  model.title = params.assoc("title").last
  model.content = params.assoc("content").last
  model.logo = params.assoc("logo").last
  model._status = params.assoc("_status").last
  model.save
  redirect to('/promoteapp/manager')
end

URI.decode_www_form_component:url解码

URI.decode_www_form :将form表单参数转成数组形式

取到数据后,通过ActiveRecord方式保存数据后

通过redirect to(‘/promoteapp/manager’)重定位到某页面

于是乎就完成了一次表单提交和处理的流程