public

Use CanCan to determine if a polymorphic association has permission via validations

  • Download Gist
polymorphic_validation_with_cancan.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
# 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.