Domanda

Ho un sistema seguente e vorrei limitare l'azione del controller degli utenti 'Segui' se il params[:id] è uguale all'utente corrente.

Io uso Cancancan (una gemma di cancan aggiornata) per far funzionare le mie autorizzazioni.

Controller / Users_Controller.rb

def follow
  Followership.create(leader_id: params[:id], follower_id: current_user.id)
  ...
end
.

modelli / user.rb

class User < ActiveRecord::Base
  has_many :followers, :class_name => 'Followership', dependent: :destroy
  has_many :followed_by, :class_name => 'Followership', dependent: :destroy
  ...
end
.

Modelli / Followership.rb

class Followership < ActiveRecord::Base
  belongs_to :leader, :class_name => 'User'
  belongs_to :follower, :class_name => 'User'
  ...
end
.

È stato utile?

Soluzione

Aggiungi una convalida sul tuo modello 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
.

Altri suggerimenti

Forse puoi usare una convalida:

#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
.


.

Ero a metà strada attraverso la scrittura quando @BroiStatse ha pubblicato

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top