一千萬個為什麽

搜索

has_many,belongs_to和評論表

我有兩個模型: SnippetSnippetComment 。它們也有自己的控制器和視圖。在 /app/views/snippets/show.html.erb 中,我有一個如下所示的表單:


SnippetComment belongs to one Snippet, and a Snippet belongs to one User. This means that I have this routing (making it non-RESTful == making it suck, as you know):

map.resources :users do |user|
  user.resources :snippets do |snippet|
    snippet.resources :snippet_comments, :as => "comments"
  end
end

因此,當我在 SnippetController#show 視圖中提交 SnippetComment 表單時,應該發出以下請求:

POST /users/x/snippets/x/comments HTTP/1.1

(其中 xUserSnippetid )。

問題是我甚至沒有收到評論提交表格,但是這樣做:

NoMethodError in Snippets#show

Showing app/views/snippets/show.html.erb where line #29 raised:

undefined method `snippet_comments_path' for

Extracted source (around line #29):

26: 
27: 

Schrijf een nieuwe reactie

28: 
29: 
30: 
31: 
32:

RAILS_ROOT: /Users/jeffatwood/Dev/youjustdontneedmyrealname

Application Trace | Framework Trace | Full Trace

/Users/jeffatwood/.gem/ruby/1.8/gems/actionpack-2.3.5/lib/action_controller/polymorphic_routes.rb:107:in `__send__'
/Users/jeffatwood/.gem/ruby/1.8/gems/actionpack-2.3.5/lib/action_controller/polymorphic_routes.rb:107:in `polymorphic_url'
/Users/jeffatwood/.gem/ruby/1.8/gems/actionpack-2.3.5/lib/action_controller/polymorphic_routes.rb:114:in `polymorphic_path'
/Users/jeffatwood/.gem/ruby/1.8/gems/actionpack-2.3.5/lib/action_view/helpers/form_helper.rb:298:in `apply_form_for_options!'
/Users/jeffatwood/.gem/ruby/1.8/gems/actionpack-2.3.5/lib/action_view/helpers/form_helper.rb:277:in `form_for'
/Users/jeffatwood/Dev/youjustdontneedmyrealname/app/views/snippets/show.html.erb:29:in `_run_erb_app47views47snippets47show46html46erb'
/Users/jeffatwood/Dev/youjustdontneedmyrealname/app/controllers/snippets_controller.rb:19:in `show'

Request

Parameters:

{"id"=>"1",
 "user_id"=>"2"}

Show session dump

Response

Headers:

{"Content-Type"=>"text/html",
 "Cache-Control"=>"no-cache"}

哦,在 snippets_controller.rb 中我有這個:

def show
  @snippet = Snippet.find(params[:id], :conditions => { :user_id => params[:user_id] })
  @new_snippet_comment = SnippetComment.new

  respond_to do |format|
    format.html
    format.xml
    format.json
  end
end

任何人都可以幫我解決這個問題嗎?謝謝

最佳答案

You have two levels of nesting ( i.e. user -> snippet -> comment) so your form_for syntax should be as follows:

form_for [@user, @snippet, @comment]

轉載註明原文: has_many,belongs_to和評論表