Well, I didn't know how to title this. This was my best guess. Here's my problem:
I'm having Issues
and Reviews
controllers. Both of them should have a Comments
controller nested.
Do I have to generate two separate scaffolds like icomment
for the Issues
and rcomment
for the Reviews
or is there a way to use the resource simultaneously for both?
These two controllers are already nested, so i guess it would get pretty messy to maintain this. What would be the best approach for this?
You can leave it at the same level as the two commentable objects:
namespace :whatever
resources :comments
resources :issues
resources :reviews
end
And force the requests to /whatever/comments
to have values for the params[:commentable_id]
(for Create, Update and Edit) and the params[:commentable_type]
(for all CRUD) ;)
An example of a nested form for the Issue model:
# issues controller
before_filter :set_issue, only: [:new, :edit, :update, :destroy]
def set_issue
@issue ||= params[:id].present? ? Issue.find(params[:id]) : Issue.new
end
# view _form
form_for @issue do |f|
f.text_field :name
f.fields_for @issue.comments.new do |ff|
ff.text_field :content
end
f.submit "Save!"
end
# Issue model
class Issue < ActiveRecord::Base
has_many :comments, as: :commentable
accepts_nested_attributes_for :comments