开发者

Best way to create Rails route for both resource (singular) AND resources (plural)?

开发者 https://www.devze.com 2023-03-04 06:26 出处:网络
I have a profile model in my application.I want to allow a user to view their own profile via /profile, so I created this route:

I have a profile model in my application. I want to allow a user to view their own profile via /profile, so I created this route:

resource :profile, :only => :show

I also want the user to be able to view other users' profiles via /profiles/joeblow, so I created this route:

resources :profiles, :only => :show

The problem is, in the second case, there is an :id parameter that I want to use to find the profile. In the 开发者_如何学编程first case, I just want to use the logged in user's profile.

This is what I'm using to find the right profile, but I'm wondering if there's a more appropriate way I could be doing this.

class ProfilesController < ApplicationController
  before_filter :authenticate_profile!
  before_filter :find_profile

  def show
  end

  private

    def find_profile
      @profile = params[:id] ? Profile.find_by_name(params[:id]) : current_profile
    end
 end

Edit: One of the problems with this method is my routes. It's not possible for me to call profile_path without passing a profile/ID parameter, meaning anytime I have to use the string '/profile' whenever I need to link there.

$ rake routes | grep profile
  profile GET    /profiles/:id(.:format) {:action=>"show", :controller=>"profiles"}
          GET    /profile(.:format)      {:action=>"show", :controller=>"profiles"}


Your routes:

resource :profile, :only => :show, :as => :current_profile, :type => :current_profile
resources :profiles, :only => :show

Then your ProfilesController

class ProfilesController < ApplicationController
  before_filter :authenticate_profile!
  before_filter :find_profile

  def show
  end

  private

  def find_profile
    @profile = params[:type] ? Profile.find(params[:id]) : current_profile
  end
end

Your Profile model

class Profile < AR::Base
  def to_param
    name
  end
end

Views:

<%= link_to "Your profile", current_profile_path %>
<%= link_to "#{@profile.name}'s profile", @profile %>
# or 
<%= link_to "#{@profile.name}'s profile", profile_path( @profile ) %>

Also: if Profile is a model, you

0

精彩评论

暂无评论...
验证码 换一张
取 消