Question: How to get a Sinatra erb to report back its referring page in params


How to get a Sinatra erb to report back its referring page in params

Answers 1
Added at 2016-12-26 18:12

For learning purposes, I am developing a Ruby/Sinatra "to do list" program. In views, I have the usual index page, which lists uncompleted tasks, and also a completed page. On both pages (and on many future user-created categories pages), there is a similar table, with similar methods for moving and deleting items. These call the same methods, or I'd like them to. But if they call the same methods, at the end of those methods the user is redirected to the index view. But if users are on the completed page, they want to stay on that page after deleting an item (or whatever).

To solve this problem, I think what I need to do is pass a variable from the erb file to the route block, reporting what view (erb file) the user was most recently on. I thought there would be some built-in Sinatra methods to report this, and I looked hard (e.g., I tried all plausible-sounding ways of accessing the request object), but I couldn't find any. Then I tried using <input type="hidden" name="pg_type" value="completed"> but for reasons totally mysterious to me, this doesn't work (maybe because Sinatra uses type="hidden" to route PUT and DELETE requests?). When I inspect the parameters with p params, I see that the pg_type param was created, but its content is an empty string ("").

An example form from (this is a template used by the other views) task_table.erb is this:

<form method="post" action="/delete/<%= %>">
  <label for="delete_button">
  <input type="hidden" name="pg_type" value="<% @pg_type %>">
  <button type="submit" name="delete">Delete</button></label>

Here is the route block for that method:

post('/delete/:id') do
  session[:message] << " " + "Deleted task!"
  redirect "/" if params[:pg_type] == "index"
  redirect params[:pg_type]  # But params[:pg_type] always == "" :-(

So how can a pass info about the referring page from my erb pages to my route blocks? Or, if my strategy for solving the problem of returning the user to the correct page is wrong or could be improved (I wouldn't be surprised), please explain.

I'd love to have any more detailed feedback on this program. Other problems I'm trying to solve are how to add unit tests of put and delete methods and how to add user accounts (not started with that though).

Answers to

How to get a Sinatra erb to report back its referring page in params

nr: #1 dodano: 2016-12-26 18:12

In your code you forgot a '=' before @pg_type:

<input type="hidden" name="pg_type" value="<%= @pg_type %>">
Source Show
◀ Wstecz