Dynamic fields using Sinatra

0

In Rails this is a relatively simple task. But I did not find anything in Sinatra's documentation stating that it was possible. I want to add fields to a form dynamically. User clicks a link and a new field is added. If desired, click on another link and the field is removed. On the front end the task is super quiet, I know. But what about persisting an arbitrary number of fields in the database? What would it be like?

    
asked by anonymous 09.08.2014 / 12:23

1 answer

1

The documentation says that Sinatra also supports optional query parameters:

  

Routes may also use query parameters:

get '/posts' do
  # matches "GET /posts?title=foo&author=bar"
  title = params[:title]
  author = params[:author]
  # uses title and author variables; query is optional to the /posts route
end
     

Source: link

So you can use a simple if to find out if a parameter exists:

require "sinatra"

get "/foo" do
  params[:bar] if params[:bar]
end

In the example above:

localhost:5678/foo            # retorna uma página em branco
localhost:5678/foo?bar=foobar # retorna "foobar"

So I think one way to solve your problem would be to create each field with a number back:

<input type="text" name="campo1"/>
<input type="text" name="campo2"/>
<input type="text" name="campo3"/>
<input type="text" name="campo4"/>

And then you could use a loop repetition to check if the field exists and does whatever it takes with it.

    
09.08.2014 / 19:39