In my example, I have a topic that I want to have a link next to to
create a new child.
So my erb, says something like:
<%= link_to ‘New Child’, { :action => “newChild”, id => topic.id } %>
However, the routing doesn’t like it because it thinks
topics/newChild
is asking for a specific topic and it can’t find one with an id of
“newChild”
What I want is the same form as I get from “New Topic” at bottom of
the page but with the parent already pre-filled with the id I send it.
Is there a better way to do this?
Thanks in advance,
Alan
In routes.rb:
map.resources :topics do |topic|
topic.resources :comments
end
With that you should be able to use this in your view:
<%= link_to “Add Comment”, new_topic_comment_path(@topic) %>
In your controller:
def new
@topic = Topic.find(params[:topic_id])
@comment = @topic.comments.build
end
Every request sent to the CommentsController will get the topic_id so
you can do nice things like listing all the comments for a particular
topic, etc.
Maybe this is answering my question, but it doesn’t seem to work.
What I want is to create a child that is also a topic (ie, a subtopic)
I tried:
map.resources :topices do |topic|
topic.resources :topics
end
and putting:
new_topic_topic_path(@topic)
That gave me a “NoMethod error”
Any suggestions?
Thanks in advance,
alan
Watch the nested resources screencast on my site.
Http://www.rubyplus.org
Free Ruby & Rails screencasts
You may want to consider introducing a new controller (Subtopics) that
specifically deals with “topics that have parent topics”. You can
still use the same model for state/persistence but you will greatly
simplify your controller and view code by giving it a single focus.
With that in mind:
map.resources :topics do |topic|
topic.resources :subtopics
end
class TopicsController < ApplicationController
def index
@topics = Topic.find(:all, :order=>:name, …)
…
end
…
end
class SubtopicsController < ApplicationController
def index
@topic.find(:all, :order=>:name)
@subtopics = @topic.children
…
end
end
This assumes a model that uses acts_as_tree or a similar data model
for connecting ‘parent’ topics with ‘child’ subtopics.