Brett
Brett

Reputation: 21

How do I handle a form in a Sinatra app deployed to a sub-URI?

Possibly a newbie question here. I'm trying to deploy a Sinatra application via Passenger and Apache. The application works perfectly when deployed at the VirtualHost root, but fails to correctly handle a form post when I try to deploy it to a sub-URI.

A very simplified version of the app follows:

test-app.rb:

require 'sinatra/base'
require 'haml'

class TestApp < Sinatra::Base

  get '/' do
    haml :ask
  end

  post '/submit' do
    if params[:test_string].nil? || params[:test_string].empty?
      redirect '/'
    end

    @test_string = params[:test_string]
    haml :result
  end
end

layout.haml:

!!!
%html
  %head
    %title Test App
  %body
    = yield

ask.haml:

%form{:action => '/submit', :method => 'post'}
  %legend
    Get a string
  %p
    %label{:for => ''} Please enter a string:
    %input{:type => 'textbox', :name => 'test_string', :id => 'test_string'}
  %p
    %input{:type => 'submit', :value => 'Submit >>>'}

result.haml:

%p== Here's your string: #{ @test_string }

What seems to be occurring is that the form POST isn't going to the correct URI -- it's seems to be ignoring the sub-URI config, and going to the VirtualHost root where, of course, there's no code to handle the route. I've checked and rechecked the Apache configuration, and that doesn't seem to be the problem.

<VirtualHost *:80>
  ServerName my.domain.com
  DocumentRoot /var/websites/home
  <Directory /var/websites/home>
    Allow from all
    Options -MultiViews
  </Directory>

  Alias /test-app /var/websites/test-app/public
  <Location /test-app>
    PassengerBaseURI /test-app
    PassengerAppRoot /var/websites/test-app
  </Location>
  <Directory /var/websites/test-app/public>
    Allow from all
    Options -MultiViews
  </Directory>
</VirtualHost>

Is there any way (other than hardcoding the form) to ensure that the form posts to the sub-URI, where my application can handle it, instead of posting to the VirtualHost root?

Upvotes: 1

Views: 117

Answers (1)

Brett
Brett

Reputation: 21

Not sure this is the best way of handling this, but I worked around the problem by using Sinatra's url helper in ask.haml:

%form{:action => "#{ url('/submit') }", :method => 'post'}
  %legend
    Get a string
  %p
    %label{:for => ''} Please enter a string:
    %input{:type => 'textbox', :name => 'test_string', :id => 'test_string'}
  %p
    %input{:type => 'submit', :value => 'Submit >>>'}

By doing that my form posted to the application's sub-URI rather than to the VirtualHost root.

Upvotes: 1

Related Questions