我遇到了Rails破坏操作的问题。我有完整的消息系统。用户可以发送,读取消息但不能删除它。 我的消息控制器是:
class MessagesController < ApplicationController
before_filter :set_user
def index
if params[:mailbox] == "sent"
@messages = @user.sent_messages.page(params[:page])
elsif params[:mailbox] == "inbox"
@messages = @user.received_messages.page(params[:page])
end
end
def new
@message = Message.new
@reply_to = User.find_by_id(params[:reply_to])
unless @reply_to.nil?
@message.recepient_id = @reply_to.id
end
end
def create
@message = Message.new(message_params)
@message.sender_id = @user.id
if @message.save
flash[:notice] = "Message has been sent"
redirect_to user_messages_path(current_user, :mailbox=>:inbox)
else
render :action => :new
end
end
def show
@message = Message.readingmessage(params[:id],@user.id)
end
def destroy
@message = Message.find(params[:id])
@message.destroy
end
private
def message_params
params.require(:message).permit(:sender_id, :recepient_id, :body, :subject, :read_at)
end
def set_user
@user = current_user
end
end
我的路线是:
resources :users do
resources :messages
end
在视图中我有删除链接(不起作用):
%h2 Your Inbox
- if @messages.size == 0
%h1 No messages in your Inbox
- else
%table.table.table-bordered
%tr
%th Subject
%th Sender
%th Sent At
- for message in @messages
%tr
%td
- if message.read?
= link_to h(message.subject), user_message_path(@user, message)
- else
= link_to "#{h(message.subject)} (unread)", user_message_path(@user, message)
%td= "#{message.sender.name}"
= link_to "Delete Message", @message, method: :delete, data: {confirm: "You sure?"}
当我点击此链接时,我有以下错误:
No route matches [DELETE]
消息的rake路由:
user_messages GET /users/:user_id/messages(.:format) messages#index
POST /users/:user_id/messages(.:format) messages#create
new_user_message GET /users/:user_id/messages/new(.:format) messages#new
edit_user_message GET /users/:user_id/messages/:id/edit(.:format) messages#edit
user_message GET /users/:user_id/messages/:id(.:format) messages#show
PATCH /users/:user_id/messages/:id(.:format) messages#update
PUT /users/:user_id/messages/:id(.:format) messages#update
DELETE /users/:user_id/messages/:id(.:format) messages#destroy
有什么想法吗? :)
答案 0 :(得分:10)
这是因为您在路径文件中使用嵌套路由:
它将生成与用户关联的路由。所以要么改变你在链接中的路径
= link_to "Delete Message", user_message_path(message.user, message), method: :delete, data: {confirm: "You sure?"}
或者,
如果要删除没有用户对象的邮件,请为邮件定义单独的路由:
resources :messages
现在,您将能够单独使用消息路由:
= link_to "Delete Message", message, method: :delete, data: {confirm: "You sure?"}
答案 1 :(得分:3)
因为您使用了嵌套路由,所以需要在link_to
中传递两个参数,即用户实例和消息实例。并明确地写下命名路由。
像这样:
= link_to "Delete Message", user_message_path(@user, @message), \
method: :delete, data: {confirm: "You sure?"}
答案 2 :(得分:1)
作为其嵌套路径,您还需要传递用户对象..
= link_to "Delete Message", user_message_path(@message.user,@message), method: :delete, data: {confirm: "You sure?"}