Reputation: 610
Have a really basic question about rails - spent hours looking on the internet for a solution - but can not find a solution.
I just need to call a method on the clicking of a link.
The idea is I need to export an xml file that is generated by a method in the controller.
firms_controller.rb (exerpt)
.....def xml
@entries = Entry.find(:all)
send_data @entries.to_xml,
:type => 'text/xml; charset=UTF-8;',
:disposition => "attachment; filename=entries.xml"
end....
I just need to call this method from the firms view page to get the xml file to download, but cannot manage to get it to work. The XML code does work - if I add it to the index method in the controller it works flawlessly.
This is some of the ways I have attempted to get the link working after reading some online articles.
<% url = url_for({:action => "xml", :controller => 'firms'}.merge(params)) %>
<%= link_to "XML", url %>
The most basic way tried
<%= link_to "XML", :action => 'xml' %>
It seems to me like something that should be very simple - but cannot get it to work.
The error I am getting:
ActiveRecord::RecordNotFound in FirmsController#show
Couldn't find Firm with ID=xml
Rails.root: /home/james/rails/KPSmart
Application Trace | Framework Trace | Full Trace
app/controllers/firms_controller.rb:25:in `show'
show method in firms_controller
def show
@firm = Firm.find(params[:id])
end
Have tried messing with the routes to get it to work with no avail.
Thanks for your help
Upvotes: 0
Views: 136
Reputation: 433
Try This
In routes write this above your resource we written for firms controller
match 'firms/xml', :controller => 'firms', :action => 'xml',:as => :firms_xml
and link this in following way
<%= link_to "XML", firms_xml_path %>
Upvotes: 2
Reputation: 14619
Check that link URL!
I don't think it's what you're expecting. When you merge two hashes via hash1.merge(hash2)
, any duplicate keys will yield those from hash2
. And since (if I recall correctly) the params
hash has :action
and :controller
keys added to it during Rails's routing process, you're having your expected route overridden by the route to the current (show) page.
You could try reverse_merge
, which would give you a more predictable result, but I'd recommend using Rails's path generation helpers to make your life even easier:
<%= link_to "XML", firm_xml_path(@firm) %>
Hope that helps!
Upvotes: 1
Reputation: 3250
This looks like a routing issue or a link issue. Do you need to pass the ID parameter to the XML controller method? Your example links aren't showing that. You need to look up how to pass parameters in your link_to helper:
http://apidock.com/rails/ActionView/Helpers/UrlHelper/link_to
If you have the default routes setup in routes.rb:
match ':controller(/:action(/:id))(.:format)'
Then your link_to should look like:
link_to "XML", :controller => "firms", :action => "xml", :id => 1234
where 1234 is the actual id you're trying to look up.
Upvotes: 1