Appending text onto current URL through link in rails

喜夏-厌秋 提交于 2020-01-06 02:42:27

问题


Lets say the current page a user is on is:

http://0.0.0.0:3000/posts?direction=asc&sort=title

Its sorted ascending, by title.

Now lets say I have a search engine, that if you searched for "chicken" for example, the url might be:

http://0.0.0.0:3000/posts?direction=asc&search=chicken&sort=title

But instead of searching, I'd like to make a link such as <a href="CODE HERE">Show all results for chicken</a> which appends &search=chicken to url, or if search already has a value, replaces it.

Is this possible?


回答1:


You can use the link_to function without a specified controller/action. Just provide the arguments you want and a URL will be created for the current page plus those parameters.

Note that you will need to use the existing params hash and merge in your additional :search item, otherwise your direction and sort arguments will be removed from the URL. Also, if there is an existing params[:search] item, it will be overwritten by the merge.

<%= link_to "Show all results for chicken", params.merge({:search => "chicken"}) %>


来源:https://stackoverflow.com/questions/4812169/appending-text-onto-current-url-through-link-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!