Rails - ユーザーは自分自身を制限します
-
20-12-2019 - |
質問
次のシステムを持っていて、params[:id]
が現在のユーザーと同じ場合は、ユーザーコントローラのアクションの「FILLOW」を制限したいと思います。
私の承認が働くためにCANCANAN(最新のCancan GEM)を使用します。
コントローラ/ users_controller.rb
def follow
Followership.create(leader_id: params[:id], follower_id: current_user.id)
...
end
.
models / user.rb
class User < ActiveRecord::Base
has_many :followers, :class_name => 'Followership', dependent: :destroy
has_many :followed_by, :class_name => 'Followership', dependent: :destroy
...
end
.
モデル/ FORLOCTERS.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