我有这个创建方法:
def create
...
grid = Tag.find_by_id(story[:tag_id]) or raise GridNotFoundError
...
event = Event.find_by_id(story[:event_id]) or raise EventNotFoundError
...
rescue GridNotFoundError
flash.now[:error] = "Please select a category"
@item = item
@years = story[:years]
@event_name = race[:name]
@country = race[:country]
@classification = race[:class]
@events = Event.all
@countries = Tag.countries
@classifications = Classification.all
@grids = Tag.grids.find(:all, :conditions => ["value != ?", "Channel Creation Grid"])
render "home/race_updates"
rescue EventNotFoundError
flash.now[:error] = "Please select an event or create a new one if you don't find your event"
@item = item
@event = story[:event_id]
@years = story[:years]
@events = Event.all
@countries = Tag.countries
@classifications = Classification.all
@grids = Tag.grids.find(:all, :conditions => ["value != ?", "Channel Creation Grid"])
render "home/race_updates"
rescue CreateEventError
flash.now[:error] = "There has been a problem creating your event."
params[:expand] = true
@item = item
@years = story[:years]
@event_name = race[:name]
@country = race[:country]
@classification = race[:class]
@events = Event.all
@countries = Tag.countries
@classifications = Classification.all
@grids = Tag.grids.find(:all, :conditions => ["value != ?", "Channel Creation Grid"])
render "home/race_updates"
rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid, ActiveRecord::RecordNotFound
flash.now[:error] = item.errors.full_messages.join(" ,")
@item = item
@event = story[:event_id]
@years = story[:years]
@events = Event.all
@countries = Tag.countries
@classifications = Classification.all
@grids = Tag.grids.find(:all, :conditions => ["value != ?", "Channel Creation Grid"])
render "home/race_updates"
end
正如你所看到的,救援几乎是一样的。救援也是 home#race_updates 方法的文字复制粘贴。
我有两个问题:
- 有什么办法让我把它擦干吗?
- 这对于一般的控制器来说是一个好的模式吗?
我曾考虑将它作为一个函数分离出来,但我需要传入 Flash 消息、项目、故事和种族变量。我觉得这不是一个优雅的解决方案,但它肯定会更干净。
我发现以这种方式编码(即引发错误并拯救它们)使我更容易分离实际的业务逻辑,并处理业务逻辑中出现的不同错误/案例。到目前为止,它有效,但我想就这是否是最佳实践或我没有按预期使用开始/救援?