实现这一点的方法是使用嵌套的路由,而不是通过
conversation_id
通过请求主体:
resources :conversations do
resources :messages, shallow: true
end
class MessagesController < ApplicationController
def create
@conversation = current_user.conversations
.find(params[:conversation_id])
@message = @conversation.messages.new(message_params) do |m|
m.user = current_user
end
if @message.save
redirect_to @conversation
else
render :new
end
end
private
def message_parameters
params.require(:message)
.permit(:body)
end
end
这是可行的,但还远远不够完美。如果
@conversation = current_user.conversations.find(params[:conversation_id])
找不到一张唱片我们得到一张
ActiveRecord::RecordNotFound
异常和404响应,而不是检查用户是否有权发布到该对话。
更好的解决方案是使用以下方法:
@conversation = Conversation.find(params[:conversation_id])
unless conversations.users.exist?(id: current_user.id)
raise SomeKindOfAuthenticationError
end
当然,你真的应该使用类似权威的东西,而不是在这里重新发明轮子。