Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lujanfernaud
Last active April 5, 2022 11:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lujanfernaud/74c631d1a7eb96b05f21d24bc6020e50 to your computer and use it in GitHub Desktop.
Save lujanfernaud/74c631d1a7eb96b05f21d24bc6020e50 to your computer and use it in GitHub Desktop.
Rails: Dynamic Path Inside Partial

Rails: Dynamic Path Inside Partial

We have a _user partial that we want to render from two different resources, passing a collection. The only thing that needs to change in the partial is the path inside the link_to helper.

We can use self.send("path", object) inside link_to to achieve this.

groups/_user.html.erb

<%= link_to user.name, self.send("#{path}", object, user) %>

events/show.html.erb

<%= render partial: "groups/user",
  collection: @event.attendees, as: :user,
  locals: {
    object: @event,
    path:   "event_attendee_path"
  } %>

groups/show.html.erb

<%= render partial: "user",
  collection: @members, as: :user,
  locals: {
    object: @group,
    path:   "group_member_path"
  } %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment