Getting the current Action in the Model


#1

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

#2

On Sun, Jan 08, 2006 at 05:49:54AM +0100, Mark H. 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


#3

On 1/7/06, Duane J. removed_email_address@domain.invalid wrote:

  • Mark
    @glazed
    if @donut.save

    end
    end

def create
@donut.glazed = true
if @donut.save

end
end

Goddamn it, now you made me hungry. :frowning:


#4

On Jan 7, 2006, at 9:49 PM, Mark H. 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 J.
(canadaduane)
http://blog.inquirylabs.com/