القضبان - منع المستخدمين من متابعة أنفسهم
-
20-12-2019 - |
سؤال
لدي نظام تالي وأرغب في تقييد إجراء وحدة تحكم المستخدمين "متابعة" إذا كان params[:id]
هو نفس المستخدم الحالي.
أستخدم cancancan (جوهرة كانكان محدثة) للقيام بأعمال التراخيص الخاصة بي.
وحدات التحكم/users_controller.rb
def follow
Followership.create(leader_id: params[:id], follower_id: current_user.id)
...
end
النماذج/user.rb
class User < ActiveRecord::Base
has_many :followers, :class_name => 'Followership', dependent: :destroy
has_many :followed_by, :class_name => 'Followership', dependent: :destroy
...
end
نماذج/followership.rb
class Followership < ActiveRecord::Base
belongs_to :leader, :class_name => 'User'
belongs_to :follower, :class_name => 'User'
...
end
المحلول
إضافة التحقق من الصحة على الخاص بك Followship
نموذج:
class Followership < ActiveRecord::Base
belongs_to :leader, :class_name => 'User'
belongs_to :follower, :class_name => 'User'
validate :doesnt_follow_self
private
def doesnt_follow_self
errors.add(:base, 'You can\'t follow yourself') if leader == follower
end
end
نصائح أخرى
ربما يمكنك استخدام التحقق من الصحة:
#app/models/followership.rb
Class FollowerShip < ActiveRecord::Base
include ActiveModel::Validations
...
validates_with FollowValidator
end
#app/validators/follow_validator.rb
class FollowValidator < ActiveModel::Validator
def validate(record)
if record.leader_id == record.follower_id
record.errors[:leader_id] << "Sorry, you can't follow yourself!"
end
end
end
لقد كنت في منتصف الطريق من خلال كتابة هذا عندما @BroiStatse
نشر
لا تنتمي إلى StackOverflow