The question at hand deals with the key topics:
- Nested Resources
- Polymorphic Associations
- Forms
We will assume we have Photos and Articles, both of which have Comments. This creates our Polymorphic Association.
#Photo Model -> photo.rb
class Photo < ActiveRecord::Base
has_many :comments, :as => :commentable
accepts_nested_attributes_for :comments
end
#Article Model -> article.rb
class Article < ActiveRecord::Base
has_many :comments, :as => :commentable
accepts_nested_attributes_for :comments
end
#Comment Model -> comment.rb
class comment < ActiveRecord::Base
belongs_to :commentable, :polymorphic => true
end
Our View to add and view Comments is shared between Photos and Articles.
#Index View
<%= form_for [@comment] do |f| %>
<%= render 'form', :f => f %>
# more code...
<% end %>
And, our resources Photos and Articles are nested in other resources as so:
# Routes.rb
namespace :galleries do
resources :photos do
resources :comments
end
end
namespace :blogs do
resources :articles do
resources :comments
end
end
Now you can see in the form above, we have our polymorphic resource, but wee need our Parent resource and the Grand-Parent resource depending upon our request path. If hard coded (never gonna do it) we would have one of these two in the form_for:
<%= form_for [:galleries, :photos, @commetns] do |f| %>
or
<%= form_for [:blogs, :articles, @commetns] do |f| %>
Assuming we can find the parent from in our CommentsController as found in many articles and Stackoverflow answers like so:
def find_medical_loggable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
end
How can we find the grand-parents and put all of this into the form_for helper?
Greatly appreciate it!