2010-01-31 25 views
0

我有兩個模型是這樣的:Rails的map.resources及助手的url

class Topic < ActiveRecord::Base 
    has_many :articles 
end 

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

我已經安裝像資源映射這樣:

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

而且我可以查看文章就好了,當我調用相應的URL(例如/:topic_slug/articles/2)。在我的文章中的觀點,我使用的部分來處理物品的創建和編輯,像這樣:

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

問題棱文我嘗試創建新文章或編輯現有的,我得到以下錯誤:

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 

有沒有人知道我要去哪裏錯了,我失蹤了?

回答

4

你需要傳遞的話題也:

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

當你只傳遞@articleform_for比它試圖基於@article正確的道路 - 這就是爲什麼你的錯誤說你沒有article_path方法。當您通過[@topic, @article]form_for時,會發現您想要撥打topic_article_path

如果你沒有任何@topic創造新的文章,那麼你可能需要指定接受的文章沒有主題新路線,所以加:

map.resources :articles 

然後:

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

將工作,但它會生成像:/articles/3 - 沒有話題部分。

0

如果你想爲文章非嵌套路線,文章分別映射以及:

map.resources :articles