2014-01-30 37 views
0

我有這三個底部路線半寧靜的路線是因爲通常申報等航線的很容易出錯:Rails的:低於

# normal routes 
resources :documents, :except => [:show, :edit, :update] 
resources :photos, :except => [:show, :index] 
... 
# error-prone routes 
get ":client_code" => "share#index", :as => :shares, :format => false 
get ":client_code/:id" => "share#show", :as => :share, :format => false 
get ":client_code/:document_id/more/:component_id" => "share#more", :as => :more, :format => false 

我得在ShareController一些應對方法與像這樣的請求:

def show 
    get_user_by_parameter 
    if get_document_by_user_or_issue and @document.is_showable? and @parameter_user == @document.user 
    ... 
end 

private 

def get_user_by_parameter 
    @parameter_user = User.where(:client_code => params[:client_code]).first 
end 


def get_document_by_user_or_issue 
    if params[:id].match(/\D/) 
    @document = Document.where(:user_id => @user.id, :issue => params[:id]).first 
    else 
    @document = Document.find(params[:id]) 
    end 
end 

我需要的路線是最小的,但是這不僅是醜陋和非RESTful的,但它是非常容易出錯。

:client_code將始終是正在查看的@document的所有者。這有點像安全檢查/擁有權有點功能。但是,由於上面列出的所有原因:是否有更好的方法來寫這個?有一個比這更好的方法。

謝謝。

基於
+0

容易出錯?什麼? – phoet

回答

1

控制器檢查:

before_filter :find_document 

def find_document 
    Document.find(params[:id]) 
end 

def is_owner?(document) 
redirect_to root_path if current_user.id != document.owner_id 
end 

是不是這樣的檢查更容易?我不知道爲什麼你有一個股票控制器,所以我不想在這裏放肆。

這將允許你這樣做:

resources :shares, only: [:index, :show] 

另外:

User.where(:client_code => params[:client_code]).first 

可重構爲:

User.find_by(client_code: params[:client_code]) 

假設你是在最新的軌道版本,否則:

User.find_by_client_code(params[:client_code]) 

讓我知道股份是什麼,我不確定我是否爲您提供完整的解決方案。

乾杯。

編輯

,如果您使用的股票提供了不同的看法,我建議這樣做:

內的控制器,

def index 
    if params[:shares] 
    render 'shares' 
    end 
end 

,除非你真的希望有一個不同的路線它。這使您不必擁有共享控制器,實質上是什麼文檔模型。

+0

感謝您的深思熟慮的答覆。 「份額」作爲「文檔」的不同視圖存在。代碼就像這樣一段時間,不知道這是一個非常好的方式,雖然用戶發送到不同的'文檔'視圖。 –