0

In my Rails app there are experiment instances and each experiment has attachments, which are represented as binary blobs in the database and can be quite big. This question is about efficiency in coding a link_to show the attachment.

Originally I had this:

<%= link_to @experiment.attachment.file_name, @experiment.attachment %>

However I was told that the Rails app would be more efficient in rendering the page with

<%= link_to @experiment.attachment.file_name, {:controller => :attachments, :action => :show, :id => @experiment.attachment_id}, {:method => :get} if ! @experiment.attachment_id.nil? %>

The justification is that the first version fetches the attachment from the database, and the second one does not, making it is better, albeit longer and uglier. Is this true?

Both versions accomplish the same thing in directing the user to the show page for an attachment and I was under the impression the first is the default way to do a link_to a record show page.

Is there a way to shorthand the second piece of code to make it less terrible with code in the view?

kassak
  • 3,974
  • 1
  • 25
  • 36
NarDmw
  • 1
  • 1

2 Answers2

0

Try using a rails route helper, use rake routes to view all your routes and then you can get something like this (don't forget to apped _path to route):

experiment_attachment_path(@experiment.attachment)
Edu Lomeli
  • 2,263
  • 20
  • 18
0

I would express this using the route path rather than using the ActiveRecord instance to load so the view can use its to_param method (which is what it is doing under the hood).

<%= link_to @experiment.attachment.file_name, attachment_path(@experiment.attachment_id) %>
Helios de Guerra
  • 3,445
  • 18
  • 23