Rails - Briefly find the parent resource of a polymorphically nested resource

Suppose I have such a polymorphic structure.

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

This is pretty ugly. Whenever we add a new thing to which it may belong, we need to add it not DRYly to this before_filter.

Is getting worse. Suppose Foos are really polymorphic things that can appear anywhere, like comments or tags. And suppose you have the following routes:

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

... now we need to worry about whether to check bar_id or baz_id first.

For more complex resources, it is possible that this will not be enough to make sure that you get the parent identifier.

Which would be ideal if we could do something like this:

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. ?

: ?

+5
1

foo.parent

- :

class Bar < ActiveRecord::Base
  has_many :foos, :as => :parent
  ...
end
+4

All Articles