我有一个以下系统,如果params[:id]
与当前用户相同,我想限制用户控制器操作“关注”。
我使用cancancan(一种最新的cancan gem)来完成我的授权工作。
控制器/ 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
答案 0 :(得分:3)
在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
答案 1 :(得分:1)
也许您可以使用验证:
#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
发布