0

I am using Rails 3.2.11. I have an action (show) that I would like to disable if a certain attribute in the model is not set. Right now I am dealing with this directly in the action:

def show
    @model = Model.find(params[:id])
    if !@model.attribute
        raise ActionController::RoutingError.new('Something bad happened')
    end
end

Is this acceptable or is there a better way of handling this situation? I would like the behavior to be the same as when a user tries to access a non-existent record.

mushroom
  • 6,201
  • 5
  • 36
  • 63

2 Answers2

0

I prefer to use that logic in a before_filter, so your show action will be clean:

before_filter :check_attribute

...

def show
  # you can use straight @model here

end
...

private

def check_attribute
  @model = Model.find(params[:id])
  if !@model.attribute
    raise ActionController::RoutingError.new('Something bad happened')
  end
end

In this way you can use it also for other actions.

Alessandro De Simone
  • 4,085
  • 6
  • 28
  • 41
-1

Yes, this is acceptable. I would personally write the conditionally as a one-liner.

raise ActionController::RoutingError.new('Something bad happened') unless @model.attribute?

A good resource for alternative methods for handling :not_found response is this question.

Community
  • 1
  • 1
deefour
  • 34,974
  • 7
  • 97
  • 90