Wahtever
Wahtever

Reputation: 3678

Rails Routing error on form submit

I am trying to implement a simple private message system using rails, and it works fine however when building the reply system, i get errors. here is the code:

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

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

and the view:

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

finally the routes:

  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

however on form submit i get this error:

No route matches {:action=>"show", :controller=>"messages"}

Thanks.

Upvotes: 1

Views: 460

Answers (1)

Sri
Sri

Reputation: 2273

I guess, As you have your form, it is sending a POST to an action that only receives GETs and that is why you get your error. You either needs to send to the right action, create (as it accepts POST) in this case or set the :method to :get.

In your view, the following is the example to change the form into get method.

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

Upvotes: 1

Related Questions