私は以下の問題があります。私は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コントローラ
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
MYポストコントローラー
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
(前の私は宝石CanCanCanや評論家と書き込み許可をしようとしたが、私ましたどのように動作するのか分からなかったので、プロジェクトから削除します)。