Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a route be created for a variable that is defined in a view's loop?

I have a route that works for my "thing"'s show view. This object is nested. This is the working route:

match 'parents/:parent_id/childs/:id/thing' => 'childs#thing', :as => :thing

My problem is that I want to have this link appear one level up, in an index of these objects. The link appears in a loop and when I use the :thing symbol for the link it says it has no route. Now I know what is wrong is that it's not getting the specific ID for the object in each iteration of the loop. But I don't know how to fix this. So basically I think what I am looking for is:

match 'parents/:parent_id/childs/(way to pass loop id goes here)/thing' => 'childs#thing', :as => :thing

Does anyone know how to do this?

like image 951
Nathan Avatar asked Feb 04 '26 22:02

Nathan


1 Answers

You can give the name you want to the parameter in the route declaration, for example :index

match 'parents/:parent_id/childs/:index/thing' => 'childs#thing', :as => :thing

Next, in the ChildController, you get the index value in params[:index]

def thing
  index = params[:index]
  # Example: find item by index using their creation date
  child = Child.order("created_at ASC").offset(index).limit(1).first

end
like image 76
Baldrick Avatar answered Feb 06 '26 13:02

Baldrick