Is it possible to get the current Controller''s action from within the Model? I have a situation where I want a piece of validation to run on edits, but not on new creates. Thanks, - Mark -- Posted via http://www.ruby-forum.com/.
On Jan 7, 2006, at 9:49 PM, Mark Haliday wrote:> Is it possible to get the current Controller''s action from within the > Model? I have a situation where I want a piece of validation to > run on > edits, but not on new creates. > > Thanks, > > - Mark >You could hack things up to work that way, but there may be a better way: use conditional validations. For example: class Donut < ActiveRecord::Base attr_accessor :glazed def glazed? @glazed end validates_numericality_of :holes, :if => :glazed? end Then in your controller: def update @donut.glazed = false if @donut.save ... end end def create @donut.glazed = true if @donut.save ... end end This approach keeps the control on the Controller side, rather than requiring your Model to know about controller names and actions. Duane Johnson (canadaduane) http://blog.inquirylabs.com/
On Sun, Jan 08, 2006 at 05:49:54AM +0100, Mark Haliday wrote:> Is it possible to get the current Controller''s action from within the > Model? I have a situation where I want a piece of validation to run on > edits, but not on new creates.This functionality is build into the validation framework. By default validations are run always, but you can pass the :on option with either :update or :create as its value. validate_acceptance_of :terms_of_service, :on => :create Aside from validations, active record objects also have a new_record? method. t = Thing.new t.new_record? # => true t.save t.new_record? # => false Thing.find(t.id).new_record? # => false marcel -- Marcel Molina Jr. <marcel@vernix.org>
On 1/7/06, Duane Johnson <duane.johnson@gmail.com> wrote:> > On Jan 7, 2006, at 9:49 PM, Mark Haliday wrote: > > > Is it possible to get the current Controller''s action from within the > > Model? I have a situation where I want a piece of validation to > > run on > > edits, but not on new creates. > > > > Thanks, > > > > - Mark > > > You could hack things up to work that way, but there may be a better > way: use conditional validations. > > For example: > > class Donut < ActiveRecord::Base > attr_accessor :glazed > > def glazed? > @glazed > end > > validates_numericality_of :holes, :if => :glazed? > end > > > Then in your controller: > > def update > @donut.glazed = false > if @donut.save > ... > end > end > > def create > @donut.glazed = true > if @donut.save > ... > end > endGoddamn it, now you made me hungry. :-(