【问题标题】:has_many, belongs_to and comment formshas_many、belongs_to 和评论表单
【发布时间】:2010-04-16 16:19:21
【问题描述】:

我有两个模型:SnippetSnippetComment。它们也有自己的控制器和视图。在/app/views/snippets/show.html.erb 我有一个这样开头的表单:

<% form_for(@new_snippet_comment) do |form| %>

SnippetComment 属于一个Snippet,一个Snippet 属于一个User。这意味着我有这个路由(making it non-RESTful == making it suck,如你所知):

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#show

显示 app/views/sn-ps/show.html.erb 在哪里 第 29 行提出:

undefined method `snippet_comments_path' for

提取的源代码(在#29 附近):

26: <% if current_user %>
27: <h2>Schrijf een nieuwe reactie</h2>
28: 
29: <% form_for(@new_snippet_comment) do |form| %>
30: 
31: <p>
32:   <%= form.text_area :body %>

RAILS_ROOT: /Users/jeffatwood/Dev/youjustdontneedmyrealname

应用程序跟踪 |框架跟踪 | 全程跟踪

/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'

请求

参数:

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

显示会话转储

响应

标题:

{"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

谁能帮我解决这个问题?谢谢

【问题讨论】:

    标签: ruby-on-rails rest routing


    【解决方案1】:

    在创建 @new_snippet_comment 时应该传递 snipped_id

    【讨论】:

    • 究竟在哪里? form_for(@new_snippet_comment, :snippet_id =&gt; @snippet.id)form_for(@new_snippet_comment, :url =&gt; { :snippet_id =&gt; @snippet.id})(添加了我不想要的查询字符串)还是在控制器中?
    • @new_snippet_comment = SnippetComment.new(:snippet_id =&gt; 5) 在控制器中
    【解决方案2】:

    您有两个级别的嵌套(即 user -> sn-p -> comment),因此您的 form_for 语法应如下所示:

    form_for [@user, @snippet, @comment]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多