다음과 같은 문제점이 있습니다. 나는 tutorial으로 처음부터 권한을 작성하고 있습니다. 그러나이 튜토리얼에서는 사용자 역할에 부울 유형이 있습니다. 내 모델 user_role에는 문자열 유형이 있습니다. 나는 그것을 만들고 싶습니다. user_role == 'admin'
이 있으면 어디서나 액세스 할 수 있습니다. user_role == 'user'
이있는 경우 작업 표시 및 색인에만 액세스 할 수 있습니다.사용자를위한 Ruby on Rails 역할
class Permission < Struct.new(:user)
def allow?(controller, action)
if user.user_role == "user"
controller == "posts" && action.in? == (%w[index show])
elsif user.user_role == "admin"
true
end
end
end
permission.rb 그리고 난 내 페이지에서 편집을 클릭 할 때 나에게 오류 준다 :
NoMethodError의를
나는 코드 파일 이름 다음 모델에 추가 한 PostsController # 정의되지 않은 메소드`user_role '편집 : nil : NilClass
어떻게 해결할 수 있습니까? 내 모델의
부
create_table "posts", force: :cascade do |t|
t.string "title"
t.text "content"
t.boolean "read"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.date "creation_date"
t.string "author"
t.integer "user_id"
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "user_role"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
내 aplication 컨트롤러 보석 CanCanCan와 학자,하지만 난에
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authorize, only: [:new, :edit, :update, :destroy, :update ]
# def after_sign_in_path_for(resource)
# app_dashboard_index_path
#end
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
end
def current_permission
@current_permission ||= Permission.new(current_user)
end
def authorize
if !current_permission.allow?(params[:controller], params[:action])
redirect_to posts_path, alert: "Not authorized"
end
end
내 게시물 컨트롤러
class PostsController < ApplicationController
before_action :find_post, only: [:show, :edit, :update, :destroy]
before_action :authorize, only: [:new, :edit, :update, :destroy, :update ]
def index
@posts = Post.all
end
def edit
end
def new
@post = current_user.posts.new
end
def show
end
def update
if @post.update_attributes(post_params)
flash[:notice] = "Data has hanged"
redirect_to post_path
else
render action 'edit'
end
end
def destroy
@post.destroy
redirect_to posts_path
end
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post
else
render 'index'
end
end
private
def find_post
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :content, :read, :author)
end
end
(이전 내가 시도했다 쓰기 권한 부여 어떻게 작동하는지 이해하지 못했기 때문에 프로젝트에서 삭제합니다).