如何使用方法:'post'将表单数据从视图发送到rails中的其他控制器?

时间:2013-05-11 01:56:44

标签: ruby-on-rails routing

<%= simple_form_for :addcomments, :url => addcomments_post_path, :multipart => true ,:method => 'post' do |f| %>
<%= f.input :title %>
<%=  f.input :body %>
<%= f.button :submit %>

这是我在帖子中添加评论的部分视图,下面是我的帖子&gt; show view

<div>
<h4>Comments </h4><br>
<%= @all_comments.each do |t| %>
  <h3><%= t.title %></h3> <br>
  <h4><%= t.body %></h4>   <br>
  <% end %>
  <%= render :partial => 'addcomment' %>
</div>

Comments_controller.rb为

class CommentsController < ApplicationController

# before_filter :load_commentable


def addcomments
@post = Post.find(params[:id])
@user = current_user
@comment = Comment.build_from(@post,@user,params[:comment])
if @comment.save
  redirect_to post_url
else
  redirect_to post_url
end
end
end

的routes.rb

resources :comments do
member  do
  post  'addcomments', to: 'comments#addcomments'
end
end

当我运行此代码并点击post-&gt; show时,我收到错误

The action 'addcomments' could not be found for CommentsController

1 个答案:

答案 0 :(得分:0)

您正在使用多态模型,因此您的第一级路线应该是“帖子”而不是“评论”。

# resources :comments do # Change this line to
resources :posts do
  member do
    post 'addcomments', to: 'comments#addcomments'
  end
end