0

我正在使用 Rails 3.2.11。如果未设置模型中的某个属性,我想禁用一个操作(显示)。现在我直接在行动中处理这个问题:

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

这是可以接受的还是有更好的方法来处理这种情况?我希望行为与用户尝试访问不存在的记录时相同。

4

2 回答 2

0

我更喜欢在before_filter中使用该逻辑,因此您的显示操作将是干净的:

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

通过这种方式,您也可以将其用于其他操作。

于 2013-02-24T22:39:24.583 回答
-1

是的,这是可以接受的。我会亲自将有条件的写成单行。

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

:not_found处理响应的替代方法的一个很好的资源是这个问题

于 2013-02-24T21:43:49.167 回答