代码之家  ›  专栏  ›  技术社区  ›  seanyboy

在Rails中,如果用户没有登录,我在哪里停止对New、Update等的访问?

  •  0
  • seanyboy  · 技术社区  · 15 年前

    我有一个进入/编辑文章的视图。

    如果用户未登录(在模型中),我想阻止他们创建或编辑帖子&我想将./posts/new视图重定向到带有“You cannot create new posts if You're logged in”消息的帖子列表。

    我尝试在posts控制器中更改“new”命令,如下所示:

      def new
    
        if !session[:user] 
          redirect_to(@posts, :notice => 'You cannot create a post unless you are logged in.')
          return
        end
    
        @post = Post.new
    
        respond_to do |format|
          format.html # new.html.erb
          format.xml  { render :xml => @post }
        end
      end
    

    但这行不通。

    我不知道我是应该把我想做的事情的逻辑放在控制器、视图还是模型中。(或三者的组合)。

    我猜我应该只把它放在一个地方(干的,等等),但我不知道在哪里。

    4 回复  |  直到 15 年前
        2
  •  1
  •   Slobodan Kovacevic    15 年前

    用户授权通常在控制器中处理,更具体地说是使用before过滤器。例如:

    class SomeController
      before_filter :authorize
    
      # the rest of your controller
    
      private
      def authorize
        # authorization code
      end
    end
    

    现在,授权代码实际上取决于您使用的gem/插件(或者您是否实现了自己的用户系统)。

        3
  •  1
  •   nathanvda    15 年前

    [免责声明:从您的问题来看,不清楚您对rails的了解程度]

    devise .

    introduction . 它很古老,但大部分仍然屹立不倒。

    others 肯定存在)。

        4
  •  0
  •   Omar Qureshi    15 年前

    某种声明性授权-如CanCan最适合这里:

    您最好使用它,而不是在控制器上编写过滤器,因为您可以在每个资源的基础上控制授权。