views:

61

answers:

2

I have two models like this:

class Topic < ActiveRecord::Base
  has_many :articles
end

class Article < ActiveRecord::Base
  belongs_to :user
  belongs_to :topic
  has_many :comments
end

I have setup the resource mapping like so:

map.resources :topics do |topic|
  topic.resources :articles
end

And I can view the articles just fine when I call the appropriate URL (e.g. /:topic_slug/articles/2). In my article's views, I use a partial to handle the creation and editing of the articles, like this:

<% form_for(@article) do |f| %>
  ...
<% end %>

The problem arrises wen I try to either create a new article or edit an existing one I get the following error:

NoMethodError in Articles#new

Showing app/views/articles/_form.html.erb where line #1 raised:

undefined method `articles_path' for #<ActionView::Base:0x103d11dd0>
Extracted source (around line #1):

1: <% form_for(@article) do |f| %>
2:   <%= f.error_messages %>
3: 
4:   <p>
Trace of template inclusion: app/views/articles/new.html.erb

Does anyone know where I am going wrong and what I am missing?

+4  A: 

You need to pass topic also:

<% form_for([@topic, @article]) do |f| %>

When you pass only @article to form_for than it tries to generate correct path based on @article - that's why your error says that you don't have article_path method. When you pass [@topic, @article] to form_for than it will quess that you want to call topic_article_path.

If you don't have any @topic on creating new article, then you probably need to specify new route that accept article without topic, so add:

 map.resources :articles

And then:

 <% form_for(@article) do |f| %> 

will work, but it will generate url like: /articles/3 - without topic part.

klew
A: 

If you want a non-nested route for articles, map the articles separately as well:

map.resources :articles
Dave Sims