Search code examples
ruby-on-railshrefparameterslink-to

Rails, get the value of link_to or detect which a href was clicked wo adding it to url


I have the list of ids and the links to the next page for every id.

    <% 
    ids.each do |p|     
    %>
    <a href="<%= show_patient_tables_hospitals_path %>"><%= p.mk1 %></a>    
    <%end%>

I want to store in the cookies what id was clicked (chosen for the next page). So, I came up with such an idea:

    <% 
    ids.each do |p|     
    %>
   <a href="<%= show_patient_tables_hospitals_path %>"><%= p.mk1 %> <%=cookies[:pat_id]%></a> 
   <%end%>

This idea is bad, because the last id will be saved in the cookies and not the one that was clicked. So I tried to do something like this:

<% 
ids.each do |p|     
%>
   <%= link_to p.mk1, show_patient_tables_hospitals_path, :id => p.mk1 %></li> 
<%end%>

And I tried to catch params[:id] in the controller:

logger.info("#### show patient params #{params}") 
{"action"=>"show_patient_tables", "controller"=>"hospitals", "locale"=>"en"}

Somehow it does not send the params[:id].

Do you have any idea how I can detect which id was clicked on, so that I can catch it in the controller? (Note: I do not want id to appear in the url!!! So, I dont want sth like this <a href="<%= show_patient_tables_hospitals_path/<%=p.mk1 %>

Thanks in advance.

Katja

edit: routes:

get '/hospitalDB/show_patient_tables' => 'hospitals#show_patient_tables'

in a hospitals_controller:

def show_patient_tables
 logger.info("#### show patient params #{params}") 
 id=params[:id]
end

Solution

  • Considering your "next page" is always the same (you don't change the link_to based on the ID), I'd try something like this:


    <%= link_to p.mk1, show_patient_tables_hospitals_path, :id => p.mk1, :class => "demo" %>
    
    $(".demo").on("click", function(e) {
        e.preventDefault();
        $.ajax({
            url: "/session",
            data: {id: $(this).attr("id")},
            success: function(data) {
                document.location.href = $(this).attr("href");
            },
            error: function(data) {
                alert("Sorry, there was an error!");
            }
        });
    });
    
    #app/controllers/application_controller.rb
    def session
        session[:next_id] = params[:id]
    end
    
    #app/config/routes.rb
    get 'session' => 'application#session'
    

    This will basically send your request to a session action in a controller, allowing you to set a session variable for your ID. After this has been done, you'll be able to redirect to the page with Ajax, and use the session variable to modify the content