Forum: Ruby on Rails Getting the current Action in the Model

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Mark H. (Guest)
on 2006-01-08 06:49
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
Duane J. (Guest)
on 2006-01-08 07:20
(Received via mailing list)
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/
Marcel Molina Jr. (Guest)
on 2006-01-08 07:33
(Received via mailing list)
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
Joe Van D. (Guest)
on 2006-01-08 10:50
(Received via mailing list)
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.  :-(
This topic is locked and can not be replied to.