Skip to content

Instantly share code, notes, and snippets.

@ericboehs
Created August 20, 2012 23:53
Show Gist options
  • Save ericboehs/3409394 to your computer and use it in GitHub Desktop.
Save ericboehs/3409394 to your computer and use it in GitHub Desktop.
Use CanCan to determine if a polymorphic association has permission via validations
# Polymorphic validation
class Comment < ActiveRecord::Base
attr_accessible :content, :user, :user_id, :commentable, :commentable_id, :commentable_type
belongs_to :commentable, polymorphic: true
belongs_to :user
validates :commentable, :user, existence: { both: false } # Via validates_existence gem
validate :can_comment?, if: [:user, :commentable_id, :commentable_type]
private
def can_comment?
if Ability.new(user).cannot?(:comment, commentable_type.classify.constantize.find(commentable_id))
errors.add(:base, :cannot_comment)
end
end
end
class Ability
include CanCan::Ability
def initialize(user=nil)
can :comment, :reviews do |review| # CanCan 2.0 syntax (use Review instead of :reviews for < 2.0)
# We only want a host or guest to comment on a review
[review.booking.guest, review.booking.host].include? user
end if user
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment