[英]Best way to create Rails route for both resource (singular) AND resources (plural)?
我的應用程序中有一個profile
模型。 我想允許用戶通過/profile
查看自己的個人/profile
,因此我創建了以下路線:
resource :profile, :only => :show
我還希望用戶能夠通過/profiles/joeblow
查看其他用戶的個人/profiles/joeblow
,因此我創建了以下路線:
resources :profiles, :only => :show
問題是,在第二種情況下,我想使用一個:id
參數來查找配置文件。 在第一種情況下,我只想使用登錄用戶的個人資料。
這就是我用來查找正確的配置文件的方法,但是我想知道是否有更合適的方法可以這樣做。
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
編輯 :這種方法的問題之一是我的路線。 在沒有傳遞profile / ID參數的情況下,我不可能調用profile_path
,這意味着每當我需要在該處鏈接時都必須使用字符串'/ profile'。
$ rake routes | grep profile
profile GET /profiles/:id(.:format) {:action=>"show", :controller=>"profiles"}
GET /profile(.:format) {:action=>"show", :controller=>"profiles"}
您的路線:
resource :profile, :only => :show, :as => :current_profile, :type => :current_profile
resources :profiles, :only => :show
然后您的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
您的Profile
模型
class Profile < AR::Base
def to_param
name
end
end
觀看次數:
<%= link_to "Your profile", current_profile_path %>
<%= link_to "#{@profile.name}'s profile", @profile %>
# or
<%= link_to "#{@profile.name}'s profile", profile_path( @profile ) %>
另外:如果個人資料是模型,則您
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.