Réda Osseili
Réda Osseili

Reputation: 23

Rails 4 - "Validate" on a single column

I would like to make a validation before updating my record. The validation should trigger only when a single column's value has changed.

  def manage_only_subordinates_schedules
    current_user = User.current
    if !current_user.manager_of(self.created_by,true)
      self.errors.add(:base, "Vous ne pouvez pas verrouiller une programmation qui a été vérouillée par un utilisateur de grade supérieur")
      return false
    end
  end

 private  :manage_only_subordinates_schedules
 validate :manage_only_subordinates_schedules, :on => :update

Is there any way we can do something like this ?

validate :manage_only_subordinates_schedules, :on => :update, :columns => [:locked]

Upvotes: 1

Views: 131

Answers (2)

Richard Peck
Richard Peck

Reputation: 76784

Votre code devrait être:

#app/models/model.rb
class Model < ActiveRecord::Base
  validate :manage_only_subordinates_schedules, on: :update, if: "locked.changed?"

  private

  def manage_only_subordinates_schedules
    current_user = User.current
    self.errors.add(:base, "Vous ne pouvez pas verrouiller une programmation qui a été vérouillée par un utilisateur de grade supérieur") unless current_user.manager_of(self.created_by,true)
  end
end

Regarde Using a string with if and unless

You can also use a string that will be evaluated using eval and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.


As a side note, you should look at authorization, especially with CanCanCan or Pundit:

#Gemfile 
gem "cancancan"

#app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    user ||= User.new # guest user (not logged in)
    can :manage, Model do |model|
      user.manager_of(model.created_by, true)
    end
  end
end

#app/views/models/show.html.erb
<% # do something if can? :manage, Model %>

Whilst not a replacement for the validation, it will give you the ability to manage the flow so that only managers can use it.

Upvotes: 0

lienvdsteen
lienvdsteen

Reputation: 206

You probably want to check out this. Let's say you have a Book model and you want to have a validation when the title changed:

validate :call_this_method, if: :title_changed?

Upvotes: 1

Related Questions