I do it this way:
In my view I have a link like this:
<%= link_to 'Show Current Inventory Levels', parts_inventory_levels_path, :target => '_blank'%>
The :target => '_blank'
causes it to open in a new tab/window
The parts_inventory_levels_path
is in the routes.rb as:
get 'parts/inventory_levels' => 'parts#inventory_levels'
So it's going to the parts controller and calling the inventory_levels
action which is:
def inventory_levels
@parts = Part.all.order(:name)
render 'inventory_levels', layout: "print_table"
end
Here's the key part, layout: "print_table"
. I have a layout file in my app/views/layout/
folder called print_table.html.erb
:
<head>
<%= stylesheet_link_tag 'print', media: 'all' %>
<%= javascript_include_tag 'application' %>
<%= csrf_meta_tags %>
<%= yield(:head) %>
</head>
<body>
<%= yield %>
</body>
So the data from my controller action calls render on inventory_levels.html.erb:
<%= link_to_function('Print this Page', 'javascript:print()') %>
<br>
<table id="parts_table" class="table pretty" border='1'>
<thead>
<tr>
<th class="sortable">Name</th>
<th class="sortable">Sku</th>
...table omitted for brevity
Note the first line, it calls the javascript:print()
function to print the page. The reason I render a separate page is I want to format that page in a very simple way that is better suited to printing. The nice thing is I am still able to use the table_sorter
javascript to sort the table before I print it.
"I was lead to believe that the second argument for link_to was the page that should be printed." That is incorrect. The second part of the link_to
is the path or url. Rails is interpreting your table_ingredients
as
<a href="/<controller name>/table_ingredients">print ingredients</a>
I don't know your controller name so I had to use a placeholder.
I could help you write the actual code but you should just be able to use what I have here applied to your code. But if you need more help please post your controller, and any applicable routes. You can probably reduce repetitive code by passing the same controller a value as to which partial you want to render (I am rendering a whole new page but the partial should also work). Also there is probably away to use AJAX.