0

I am trying to implement a policy that restricts the creation of a post to either admin or a business. In turn only the record owner(business) who created the post or admin can edit. But i get an error saying 'undefined method user' can anyone help out here?

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
Fdwillis
  • 1,050
  • 9
  • 21
  • Two things: (1) will you post the output of your error because there isn't enough information listed to debug it, and (2) please show the entire application policy so i can see how the file is set up. – nikkon226 Jan 20 '15 at 12:41

1 Answers1

0

If you got an "undefined method user" error, that means that the user is nil, and you are calling policy(@post).edit? in your show view of post, that means that it searches through the edit method defined in your post_policy.rb file (or directly to your application_policy.rb if you don't have a post_policy.rb file) def edit?, which in turn calls the update method def update? and finally the update method is being called as:

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

Which means that user is nil, and you are calling record.user, that's the problem here, because record is not calling anything, you need to double check your post model and make sure a post belongs to a user.

class Post < ActiveRecord::Base
  belongs_to :user
end
bntzio
  • 1,274
  • 14
  • 27