1

I have a news page containing several news with pagination. I want to allow the user to view the new's details and when he clicks on a "back" button, the view goes to the page the user was previously on. My idea was to add a parameter to the link_to which brings the user on the show page, but this doesn't seem to work:

<%= link_to news_path(new.id, :back_page => params[:page]) do %>
    <span class="glyphicon glyphicon-eye-open"></span>
<% end %>

I would want the url rendered to be something like this: news/2?back_page=2. But I always get news/2.

How can I do this?

Thanks.

Edit

Here's how news_path looks like in my routes: http://pastebin.com/EAhDQyf4

actaram
  • 2,038
  • 4
  • 28
  • 49

3 Answers3

1

Well this is not a problem of link_to, can you post how news_path looks in your routes file?

Ideally above news_path(new.id, :back_page => params[:page]) should generate path as you expected.

Another way to do would be, but I won't recommend it. Because you should be able to achieve it using path helpers.

<%= link_to "something", "#{news_path(new.id)}?back_page=#{params[:page]}" do %>
   <span class="glyphicon glyphicon-eye-open"></span>
<% end %>  
Sumit Mahamuni
  • 302
  • 1
  • 6
  • @BishopBarber Go to rails console and try following `app.news_path(new.id, :back_page => 'somepagenumber')` This should generate path you are looking for. – Sumit Mahamuni Mar 15 '15 at 18:05
  • Interestingly enough, the `back_page` parameter is rendered as wanted. – actaram Mar 15 '15 at 18:08
  • I found out my problem and I really feel stupid. It's just that when I go to the news index page, the page parameter is not given. It is only given when I browse through pages. So my back_page parameter receives nothing. I thought normally I would still see `back_page=`, that's why I didn't think that would be the problem at first, but it is! Thanks a lot for the help. I wasn't sure how to use link_to, that's why I was looking in the wrong direction. – actaram Mar 15 '15 at 18:25
1

I resolved my problem. Make sure the value you give to your additional parameters is something. When I go to the news index page, even though the selected page is the first one, there is no parameter page=1. The parameter only appears once click on a different page (or you go to another page and come back to the first one). If you give an additional parameter to the link_to and its value is nothing, the rendered link will be (in my case):

<a href="/news/2" />

Instead of:

<a href="/news/2?back_page=" />

So you might get trapped, just like I was.

actaram
  • 2,038
  • 4
  • 28
  • 49
0

Here example:

link_to "Nonsense search", searches_path(foo: "bar", baz: "quux")
# => <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
  • I know, I visited [this post](http://stackoverflow.com/questions/2695538/add-querystring-parameters-to-link-to). But I don't see what's wrong with my link_to. Can you explain? – actaram Mar 15 '15 at 17:58