Rails - Pundit undefined方法'用户'

时间:2015-01-13 07:09:41

标签: ruby-on-rails devise pundit

我正在尝试实施一项政策,将帖子的创建限制为管理员或企业。反过来,只有创建帖子或管理员的记录所有者(业务)才能编辑。但我得到一个错误,说“未定义的方法用户'谁能在这里帮忙?

Schema.rb

create_table "users", force: true do |t|
    t.string   "name"
    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.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    t.string   "unconfirmed_email"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "role"

create_table "posts", force: true do |t|
    t.string   "name"
    t.string   "title"
    t.text     "content"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "user_id"
  end

User.rb

def admin?
    role == 'admin'
  end

  def biz?
    role == 'biz'
  end

Post_controller

def edit
    @post = Post.find(params[:id])
     authorize @post
  end

Post.show.html.erb

<% if policy(@post).edit? %>
    <%= link_to 'Edit', edit_post_path(@post) %> |
  <% end %>

Application.policy

def create?
    user.present? && ( user.admin? || user.biz?)
  end

  def new?
    create?
  end

  def update?
    user.present? && (record.user == user || user.admin?)
  end

  def edit?
    update?
  end

1 个答案:

答案 0 :(得分:0)

如果您有“未定义方法用户”错误,则表示用户为,并且您在中呼叫policy(@post).edit?显示帖子的视图,这意味着它会搜索post_policy.rb文件中定义的编辑方法(如果没有post_policy.rb文件,则直接搜索到application_policy.rb) def edit?,后者又调用更新方法def update?,最后将更新方法调用为:

def update?
  user.present? && (record.user == user || user.admin?)
end

这意味着用户为零,而您正在调用record.user,这就是问题,因为record没有调用任何内容,您需要仔细检查您的帖子模型并确保帖子属于用户

class Post < ActiveRecord::Base
  belongs_to :user
end