深度嵌套资源表单

时间:2014-05-30 16:00:37

标签: ruby-on-rails ruby ruby-on-rails-4 form-for nested-resources

我正在努力让这个工作,我已经阅读了很多,但在这里找不到问题。

的routes.rb

  resources :scripts do
    resources :reviews
    resources :issues do
      resources :comments
    end
  end

comments_migration

create_table :comments do |t|
  t.integer :issue_id
  t.integer :user_id
  t.text :body

  t.timestamps
end

控制器动作

  def create
    @issue = Issue.find(params[:issue_id])
    @comment = current_user.comments.build(comment_params)
    @comment.issue_id = @issue.id

    if @comment.save
      redirect_to @comment, notice: 'Comment was successfully created.'
    else
      render :new
    end
  end

  def new
    @issue = Issue.find(params[:issue_id])
    @comment = current_user.comments.new
    @comment.issue_id = @issue.id
  end

现在,在我的Issues/Show视图中,我想添加用于添加评论的表单:

<%= form_for [@issue, @comment] do |f| %>
  <div class="field">
    <%= f.label :body %><br>
    <%= f.text_area :body %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

路线:

                          POST   /scripts/:script_id/issues/:issue_id/comments(.:format)          comments#create
 new_script_issue_comment GET    /scripts/:script_id/issues/:issue_id/comments/new(.:format)      comments#new
edit_script_issue_comment GET    /scripts/:script_id/issues/:issue_id/comments/:id/edit(.:format) comments#edit
     script_issue_comment GET    /scripts/:script_id/issues/:issue_id/comments/:id(.:format)      comments#show
                          PATCH  /scripts/:script_id/issues/:issue_id/comments/:id(.:format)      comments#update
                          PUT    /scripts/:script_id/issues/:issue_id/comments/:id(.:format)      comments#update
                          DELETE /scripts/:script_id/issues/:issue_id/comments/:id(.:format)      comments#destroy
            script_issues GET    /scripts/:script_id/issues(.:format)                             issues#index

这给了我First argument in form cannot contain nil or be empty

虽然请求信息显示:

{"action"=>"show", "controller"=>"issues", "script_id"=>"10", "id"=>"8"}

我还必须在评论中加入:script_id吗?

我在这里缺少什么?

3 个答案:

答案 0 :(得分:1)

您缺少该表单是基于new操作构建的,而不是create上构建的。您还需要在那里声明这些变量。

答案 1 :(得分:1)

这是因为form_for中的参数为零。您应该在show动作中初始化它。你不需要script_id

class IssuesController < ApplicationController
    def show
     ..
     @comment = @issue.comments.build
     ..
end

修复未定义的路径错误。您需要稍微修改form_for。

<% @form_for @comment, url: script_issue_comments_path(@issue.script_id, @issue) do |f| %>
...
<% end %>

答案 2 :(得分:1)

您可以使用简单的form_for来创建评论:

form_for @issue.comments.build, url: script_issue_comments_path(params[:script_id], @issue) do |f|
  f.text_area :body
  f.submit "save"
end