Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.