Search code examples
ruby-on-railsmodel-view-controllercode-organizationproject-organization

How should I organize the controller(s) for a model with differing views for the same action(s)?


I have a User model that, in my mind, has two show actions:

  • A 'show' performed on a user's own record (to view their private profile)
  • A 'show' performed other user records (to view their public profile)

I've thought of several different ways I could organize and implement this functionality, but I'm curious what the 'Rails Way' is to do it.

The URLs should be distinct (domain.com/account vs. domain.com/profile/someuser), which naturally leads me to the desire to have multiple views to represent the different viewpoints of this action.

Option one would be to create two controllers with a different show action and view to serve the requests.

Option two would be to place both actions in one controller with action names that are essentially duplicates (or forced non-duplicates, such as 'show' vs. 'show_public').

Option three would be to use one controller and one action that processes each request conditionally based on some unique bit of data: the route from which it was called, whether or params[:id] is populated, etc.

What's the 'Rails Way' to do this?


Solution

  • Default routes, controller method and view for any user, nothing special here.

    For current_user:

    • pick an authentication gem (e.g. authlogic) with a current_user feature
    • add a route, e.g. /me
    • in the user controller, define a new method, e.g.: me (similar to show) which always use current_user to fetch @user
    • a new me.html.erb view to display current user specific information

    Hope it helps