【问题标题】:Validating ownership of a mass assigned model using shallow routes使用浅路径验证质量分配模型的所有权
【发布时间】:2012-02-07 02:09:01
【问题描述】:

我有两个模型的嵌套路由,如下所示:

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 没有在参数中传递。

但我在想也许我应该在模型中进行检查(检查插入章节的书是否属于 current_user)

【问题讨论】:

    标签: ruby-on-rails validation nested-forms


    【解决方案1】:

    我用这样的结构解决了这个问题(我有更深层次的资源嵌套,比如作者 -> 书 -> 页面,作者 -> 图片,...):

    class ChaptersController < SecurityController < ApplicationController
    

    (只是逻辑)

    AppController 处理检查调用,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)(或左右)(例如,将页面从一本书移动到另一本书)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多