1

I have a list of User objects in an index view. For each user, I am displaying a name with a link_to call for editing the user like so:

<% @users.each do |u| %>
  <%= link_to u.name, edit_user_path(u) %><br/>
<% end %>

I want to use a different edit path based on the user's role attribute (e.g. employee, manager, etc). I have edit_employee_path, edit_manager_path, etc in my routes.

What's the best way dynamically determine the 2nd parameter to link_to? I can hack this up with a bunch of ugly if/else code but I want to do it the most idiomatic Rails way.

1
  • what is your controller and actions to where you want to make routing? Commented Apr 2, 2013 at 18:42

2 Answers 2

5

how about a helper method

in your may be users_helper or any other helper of your choice

def edit_path_by_type(user)
   user.role == "Employee" ? edit_employee_path(user) : edit_manager_path(user)
end

and in your view

<%= link_to u.name, edit_path_by_type(u) %>
Sign up to request clarification or add additional context in comments.

Comments

2

You could use a Helper module to determine the *_path method to run. For example:

module UsersHelper
  def edit_url(user)
    case user.role
    when :employee
      employee_edit_path(user)
    when :manager
      manager_edit_path(user)
    else
      edit_user_path(user)
    end
  end
end

If your path methods are named in a very consistent way, you might be able to invoke a dynamically-constructed method, such as:

<%= link_to u.name, send(:"#{u.role}_user_edit_path", u) %><br/>

but you'd need to be careful that a method with the appropriate name always exists.

3 Comments

I don't know how "careful" you'd need to be; validations should prevent your role from ever containing a value that isn't supported by a path helper. I guess that's sort of careful.
Yeah, I guess having validations to begin with could be considered "being careful" here
Exactly what I need Stuart M. Thanks!

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.