0

I've got a nested resource:

def workspace
  has_many :instances
end

def instance
  belongs_to :workspace
end

and some nested routes

 resources :workspaces do 
   resources :instances do 
   end 
 end 
 resources :instances

That way, I can visit the following path and get the same result:

workspaces/1/instances 
/instances 

On my 'view/instances/index.html.erb' I have a custom pagination link, where I reload the page with additional params.

If I am in workspaces/1/instances, the link should be:

= link_to "← Previous", workspace_instances_path(:param => "data")

But, if I am in /instances:

= link_to "← Previous", instances_path(:param => "data")

How can I have a single link_to, that works for both routes? Preferably without listing all possible cases, just a single line

3
  • "all possible cases", there's just 2 cases no? Commented Feb 21, 2017 at 14:05
  • yes, there are currently 2. I thought there could be a helper or something to generate the path Commented Feb 21, 2017 at 14:10
  • I think you'll need to write one yourself api.rubyonrails.org/classes/ActionController/Helpers.html . Or simply put the logic straight into the erb file , that would work. But there's no way out of asking what action the view belongs to as far as I can see (a simple if) Commented Feb 21, 2017 at 14:18

1 Answer 1

1

link_to lets you specify the controller and action in place of the named route. Assuming that the same controller action will handle the request you could specify the controller and action

link_to "previous", :controller => "instances", :action => "my_action", :data => "data"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I also discovered '=link_to"previous",polymorphic_path([workspace,Instance]', but it doesn't work if additional nested resources are added. Your soluction works perfectly

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.