我想弄清楚如何在我的Rails 4應用程序中使用pundit。Rails 4 - 權威 - 創建策略
我有一個配置文件視圖,其中我想顯示一個鏈接來創建一個新項目,並受權限授權。
我曾嘗試以下每個配方:
<%# if policy(Project.new).create? %>
<%# if policy(Project).create? %>
<%# if policy(@project).create? %>
<%# if policy(Projects).create? %>
<% if policy(project).create? %>
<%= link_to 'CREATE A PROJECT', new_project_path, :class=>"btn btn-info" %>
<% end %>
項目和配置文件之間的關聯是:
項目
belongs_to :profile
檔案
has_many :projects, dependent: :destroy
我的項目的政策有:
def new?
true
# create?
end
def create?
true
end
當我嘗試使用該線路縱斷面圖:<% if policy(Project).create? %>
我得到一個錯誤,指出:
錯誤的參數數目(假設2,預計0)
當我嘗試在配置文件視圖中使用此行:<% if policy(@project).create? %>
我得到一個錯誤,指出:
錯誤的參數數目(假設2,預計0)
當我嘗試使用在縱斷面圖中這條線:<% if policy(Projects).create? %>
我得到一個錯誤,說:
無法找到零的政策
當我嘗試在縱斷面圖中使用此行:<% if policy(project).create? %>
我得到一個錯誤,指出:
未定義的局部變量或方法'項目」的 <#:0x007faf5255d468>難道你意思是? project_url
是不是有什麼特別的,我需要做測試的項目授權,如果視圖頁面在不同的模式(如曲線,測試授權該配置文件至於是否可以創建一個項目)?我卡住了,並猜測如何解決這個問題。
在我的項目控制,我有一個創建方法:
def create
@project = Project.new(project_params)
@project.profile = current_user.profile
respond_to do |format|
if @project.save
format.html { redirect_to @project }
format.json { render :show, status: :created, location: @project }
else
format.html { render :new }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
該策略的初始化器:
class ProjectPolicy < ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@user = user
@record = record
end
你的'def create'方法是什麼? –
@KieranAndrews - 我在文章中添加了創建動作 – Mel
您的'link_to'CREATE A PROJECT''文件是什麼視圖文件? –