model view controller - Trying to Delete Message from List with Rails -
so have simple list of messages users can submit. i'm trying put delete button (that works) each message. can see here error entirely different action if click button. i'm not totally sure went wrong. guess i'm out of depth in controller area. here applicable files.
routes.rb:
rails.application.routes.draw root 'messages#index', as: :home '/new' => 'messages#new', as: :edit resources :messages post '/new' => 'messages#create', as: :create delete 'messages/:id' => 'messages#destroy', as: :delete
the relevant controller:
class messagescontroller < applicationcontroller def index @messages=message.all end def new @messages=message.new end def destroy @messages=message.find(params[:id]) @messages.destroy end def create @messages = message.new(message_params) if @messages.save redirect_to '/' else render 'new' end end private def message_params params.require(:message).permit(:content, :subject) end end
the relevant view:
<div class="main"> <div="messages"> <%@messages.each |t|%> <h2 class="subject"><%=t.subject%></h2> <p class="content"><%=t.content%></p> <%=link_to "delete message", delete_path(t)%> <% end %> <%=link_to "create message", edit_path%> </div> </div>
you need pass method delete
well, otherwise perform get
request. here's how:
<%=link_to "delete message", delete_path(t), :method => 'delete' %>
remember if not mention method
in link_to
, default taken get
. have explicit other http methods.
edit:
either use resources :messages
, or use routes wrote yourself. using resources :messages
bit easier, , preferred way.
using resources :messages
, you'd have write:
<%= link_to "delete message", t, :method => 'delete' %>
edit 2:
you getting error template missing
, because in destroy
method, neither render
ing anything, nor redirect_to
ing anything. after destroy
object, have tell should go. if want user go messages page after he/she destroy
s record, need add following line end of method:
redirect_to messages_path
Comments
Post a Comment