1

I'm new to rails and I'm trying to link to a specific method within a controller. My controller is called OrganismsController and the method is upload_reference_file. Through looking at other similar questions I now have a link_to working as

<%= link_to "Upload Reference Sequence", :controller => :organisms, :action => :upload_reference_file %>

However, I need to pass in the current organism to the method upload_reference_file. I've tried doing

<%= link_to "Upload Reference Sequence", :controller => :organisms, :action => :upload_reference_file(organism) %>

but rails complains that the above code is not correct syntax. Inside of my routes file I have the method matched to the controller action as

match '/organisms/upload_reference_file' => 'organisms#upload_reference_file'

Any help is very much appreciated. Thanks!

3
  • Defining "doesn't work" is almost always a good idea. Is the route defined as a restful action on a member? Commented Oct 26, 2011 at 15:38
  • I edited the question a bit for clarification. I tried doing something along the lines of <%= link_to "Upload Reference Sequence", upload_reference_file_organism_path(organism) %>, but it to did not work. Commented Oct 26, 2011 at 15:43
  • you must declare using @organism in your controller Commented Oct 26, 2011 at 15:46

1 Answer 1

2

You should define a RESTful action as described in the "Adding More RESTful Actions" section of the Rails Routing docs. This will create a helper method accepting a path and allow more natural usage.

For example, if you have no additional member actions:

resources :organisms do
  get 'upload_reference_file', :on => :member
end

You'll then have a upload_reference_file_organism_path, turning your link_to into:

<%= link_to "Upload Reference Sequence", upload_reference_file_organism_path(organism) %>

(In case this needs tweaking, you can get the created path name by running rake routes; my memory isn't so good.)

Sign up to request clarification or add additional context in comments.

2 Comments

I just got match '/organisms(/upload_reference_file(/:id))' => 'organisms#upload_reference_file' to work by hard coding in the id being passed in the url, but, I like this approach a lot better. It seems to follow the rails construct more. Thanks!
@PhillipWhisenhunt Yep, this way is definitely cleaner and more Rails-y :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.