私がこのような多形構造を持っているとしましょう。
map.resources :bar, :has_many => :foo
map.resources :baz, :has_many => :foo
map.resources :qux, :has_many => :foo
class Foo
belongs_to :parent, :polymorphic => true
end
class FooController < AC
before_filter :find_parent
...
private
def find_parent
# ugly way:
@parent = if params[:bar_id]
Bar.find(params[:bar_id])
elsif params[:baz_id]
Baz.find(params[:baz_id])
elsif params[:qux_id]
Qux.find(params[:qux_id])
end
end
end
それはかなり醜いです。それが属する可能性のある新しいものを追加するときはいつでも、そのbefore_filterに非DRYlyで追加する必要があります。
それも悪化します。Foosは、コメントやタグのように、どこにでも表示される可能性のある本当に多形的なものであると仮定します。そして、次のルートがあるとします。
map.resources :bar, :has_many => :foo do |bar|
bar.resources :baz, :has_many => :foo
end
map.resources :qux, :has_many => :foo do |qux|
qux.resources :baz, :has_many => :foo
end
...ここで、最初にbar_idとbaz_idのどちらをチェックするかを心配する必要があります。
より複雑なリソースの場合、これでは親のIDを確実に取得するのに十分ではない可能性があります。
理想的なのは、次のようなことができるかどうかです。
def get_parent
# fetch the parameter that immediately preceeded :id
@parent = if x = params.before(:id)
# polymorphic find
x.key.to_s[0..-4].classify.constantize.find x.value
end
end
結局のところ、私たちのルートは、URL内のパラメーターの順序によって、すでに親をエンコードしています。なぜその情報を破棄するのですか?
だから:これはどのように行うことができますか?