1

我正在尝试使用 Rails 实现一个简单的私人消息系统,它工作正常,但是在构建回复系统时,我得到了错误。这是代码:

def show
  @message = current_user.messages.find(params[:id])
    if @message != nil
      @sender = User.find(@message.id).email
      @replies = @message.replies
      @reply = Reply.new
      @reply.message_id = params[:id]
      @reply.user_id = current_user.id
   else
      index_redirect
   end

结尾

  def reply
    @reply = Reply.new(params[:reply])
    if @reply.save
      set_flash "Reply sent"
      show_redirect
    else
      set_flash "Error, please try again"
      show_redirect
    end
  end

和观点:

<h1>Messages#show</h1>
<h2>replies</h2>
<div>
    <%- @replies.each do |reply| %>
        <%= content_tag :span, reply.content %>
        <%= content_tag :span, reply.created_at %>
        <%= content_tag :span, User.find(reply.user_id).email %>
    <% end %>

    <%= form_for @reply, :as => :reply, :url => { :action => :reply } do |reply| %>
        <%= reply.text_area :content %>
        <%= reply.submit "Reply" %>
    <% end %>
</div>

最后是路线:

  resources :messages do
    collection do
      delete 'destroy'
      post   'reply'
    end
  end



 messages DELETE /messages(.:format)            messages#destroy
      reply_messages POST   /messages/reply(.:format)      messages#reply
                     GET    /messages(.:format)            messages#index
                     POST   /messages(.:format)            messages#create
         new_message GET    /messages/new(.:format)        messages#new
        edit_message GET    /messages/:id/edit(.:format)   messages#edit
             message GET    /messages/:id(.:format)        messages#show
                     PUT    /messages/:id(.:format)        messages#update
                     DELETE /messages/:id(.:format)        messages#destroy

但是在提交表单时我收到此错误:

没有路由匹配 {:action=>"show", :controller=>"messages"}

谢谢。

4

1 回答 1

1

我想,当你有你的表格时,它正在发送一个POST只接收的动作,GETs这就是你得到错误的原因。在这种情况下,您要么需要发送到正确的操作create(因为它接受POST),要么设置:method:get.

在您看来,以下是将表单更改为get方法的示例。

<%= form_for @reply, :as => :reply, :url => { :action => :reply }, :html => {:method => :post} do |reply| %>
  <%= reply.text_area :content %>
  <%= reply.submit "Reply" %>
<% end %>
于 2013-04-02T15:02:08.857 回答