【问题标题】:Authentication and authorization in a Rails EngineRails 引擎中的身份验证和授权
【发布时间】:2012-05-16 15:49:19
【问题描述】:

我正在尝试从 Rails 应用程序中提取博客模型和控制器。我有一个名为 Blog 的 Rails 引擎,我将把它安装在主应用程序的 /blog 路由上。

在我的 Blog 引擎中,我有一个 PostsController,它具有正常的 CRUD 操作。问题是我想使用主要 Rails 应用程序中的身份验证方法。

# app/controllers/blog/posts_controller.rb
module Blog
  class PostsController < ApplicationController
    # Basically I want to have access to the require_login method
    # from the main app.
    before_filter :require_login, only: [:new, :create]

    def new
      @post = Post.new
      authorize! :create, Post
    end
  end
end

我需要访问 User 模型,以便检查 CanCan 的授权能力。例如,只有管理员可以创建博客文章。

# app/models/blog/ability.rb
module Blog
  class Ability
    include CanCan::Ability

    def initialize(user)
      user ||= User.new

      # The user.admin? method is defined on the User class
      # from the main rails app.
      if user.admin?
        can [:create, :update], Post
      end
    end
  end
end

有没有办法完成这些事情?

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3.1 rails-engines


【解决方案1】:

复制来自 cmets 的答案,以便从“未回答”过滤器中删除此问题:

看看我是如何解决类似问题的 - How get Devise's current_user method in Rails Engine

~回答wildDAlex

或者这个2,How to call a parent app's helper method from a rails 3.1 engine

~回答westonplatter

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 2010-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多