views:

306

answers:

2

I'm using Authlogic. I've got an Entry model and there is a validation method that I want to skip if the request was made by a logged in user (anonymous users are also allowed to create entries). I assume that UserSession.find would not be usable from inside the Entry model like it is from a controller. What is the best way to handle this situation? Do I need to write a custom save method of some sort and call it programmatically from the EntriesController? Or is there a way to check for login state from inside a model? I'm guessing that I wouldn't want to do that anyway, since the model should be in charge of object state and not application state.

+2  A: 

Create a virtual attribute on Entry called logged_in.

attr_accessor :logged_in

In the controller, set entry.logged_in to true if the user is logged in, false if not. Then you can use that attribute in the validation method.

validate_on_create :my_check

def my_check
  unless self.logged_in?
    # add errors
  end
end
Jonathan Julian
A: 

You can use

valide_on_create :my_check, :unless => logged_in?
Boris Barroso
There is no `logged_in?` functionality inside this model.
Jimmy Cuadra