【发布时间】: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
有没有办法完成这些事情?
【问题讨论】:
-
看看我是如何解决类似问题的 - stackoverflow.com/questions/10668874/…
-
@wildDAlex 或 westonplatter - 如果您想将解决方案概括为您自己的答案,我将删除我的答案。 (请参阅meta.stackexchange.com/questions/90263/…,详细说明为什么这样做会有所帮助。)谢谢!
标签: ruby-on-rails ruby-on-rails-3.1 rails-engines