2012-01-10 67 views
1

質量分配模型的所有權,我有兩個型號,像這樣一個嵌套的路線:驗證使用淺路線

resources :books do 
    resources :chapters, :shallow => true 
end 

,並希望能有一本書的章節的嵌套形式。

如何檢查每個質量分配的章節書是否屬於用戶。

我試圖將它添加到控制器像這樣

class ChaptersController < ApplicationController 
    before_filter :check_ownership_of_chapters_book 

    def check_ownership_of_chapters_book 
    if Book.find(params[:book_id]).author != current_user 
     flash[:error] = "You are not the author of the book you are adding the chapter to" 
     redirect_to root_url 
    end 
    end 

    ... 

它產生這個錯誤

爲本書的ID「沒有ID找不到書」沒有通過param。

但我想,也許我應該做的模型檢查(檢查該章插入本書屬於CURRENT_USER)

回答

0

我解決了這個具有這樣的結構(和我有像作者ressources有更深的嵌套 - >書籍 - >頁,作者 - >圖片,...):

class ChaptersController < SecurityController < ApplicationController 

(只是邏輯)

其中的AppController hanldes退房通話和SecurityController像這樣處理「檢查檢查」(我想要監視AppicationController儘量少

class AppicationController 
    #check-call 
    before_filter do 
     raise SiteForbiddenException.new(foo) unless check_permissions 
    end 
end 


class SecurityController < ApplicationController 

    def check_permissions 
     false 
    end 

    #check-check 
    def check_permission_from(id_val) 
     id_val={ page_id: Pageelement.find(id_val[:pageelement_id]).page_id } if id_val[:pageelement_id] 
     id_val={ book_id: Page.find(id_val[:page_id]).book_id } if id_val[:page_id] 

     if id_val[:book_id] 
      return true if ... check author from book_id ok 
     end 
     raise SiteForbiddenException.new(foo) unless check_permissions 
    end 

end 

class PageController < SecurityController 
    def check_permissions 
     return true if action_name=='public' 
     check_permission_from(page_id: params[:page_id]) 
    end 
end 

所以,如果我忘記的PageController的def check_permissions ...,我得到一個異常

而且我可以從任何其他控制器使用check_permission_from(page_id: @page_id)(左右)如果需要的話(例如,從一本書翻到另一本書)