For some reason I can''t solve this one ... I''m trying to skip a custom validation on a model when a certain controller accesses it. Is this possible? I''m thinking that I would need something this, but I can''t figure out the syntax: def validate unless current_controller == ''admin/users'' errors.add(''password'', ''and confirmation do not match'') unless password_confirmation == password end end TIA
On Oct 26, 2005, at 4:56 PM, cleaner416 wrote:> For some reason I can''t solve this one ... I''m trying to skip a > custom validation on a model when a certain controller accesses > it. Is this possible? I''m thinking that I would need something > this, but I can''t figure out the syntax: > > def validate > unless current_controller == ''admin/users'' > errors.add(''password'', ''and confirmation do not match'') > unless password_confirmation == password > end > end > >It looks like you''re doing this a little backwards... at least, you''re causing the model to "control" the controller by imposing a rule that says "Only certain controllers can skip this validation". If I were to tackle this problem, I would do it in one of two ways: role-based permissions, or else an "admin_mode" attribute in your model. To accomplish the latter (probably the simpler of the two): class User < ActiveRecord::Base attr_accessor :admin_mode # [other stuff in the model goes here] def not_admin_mode (not admin_mode) end validates_confirmation_of :password, :if => :not_admin_mode end Then in the controller, I would do the following before attempting to save: class Admin::UsersController < ApplicationController def update @user = User.find(params[:id]) @user.admin_mode = true # Note that this attribute will NOT be saved in the db if @user.save # Success else # Failure end end end Duane Johnson (canadaduane)
Julian ''Julik'' Tarkhanov
2005-Nov-03 23:03 UTC
Re: Change model validation depending on controller?
On 27-okt-2005, at 1:56, cleaner416 wrote:> For some reason I can''t solve this one ... I''m trying to skip a > custom validation on a model when a certain controller accesses > it. Is this possible? I''m thinking that I would need something > this, but I can''t figure out the syntax: > > def validate > unless current_controller == ''admin/users'' > errors.add(''password'', ''and confirmation do not match'') > unless password_confirmation == password > end > endThis is wrong. If your form doesn''t SEND the confirmation in the first place it will not be required by ActiveRecord validation. Which transforms your code into the view: <%= password_field ''user'', ''password'' %> <% unless controller.controller_name == ''admin/users'' %> <%= password_field ''user'', ''password_confirmation'' %> <% end %> -- Julian "Julik" Tarkhanov