私はこの作成方法を持っています:
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 メソッドの文字通りのコピー アンド ペーストでもあります。
2 つの質問があります。
- これを乾かす方法はありますか?
- これは一般的にコントローラーにとって良いパターンですか?
関数として分離することを考えましたが、フラッシュ メッセージ、アイテム、ストーリー、レース変数を渡す必要があります。エレガントなソリューションではないように感じますが、確かにクリーンになります。
このようにコーディングする (つまり、エラーを発生させて解決する) と、実際のビジネス ロジックを本来あるべき姿に分離し、ビジネス ロジックで発生するさまざまなエラー/ケースを処理することが容易になることがわかりました。これまでのところ動作していますが、これがベスト プラクティスなのか、意図したとおりに begin/rescue を使用していないのかについて意見を集めたいですか?