【发布时间】:2017-05-16 15:09:05
【问题描述】:
所以我有一个Message 模型和一个ChatRoom 模型。
当我显示一个聊天室时,我在 ChatRoom 控制器上使用show 操作。在此操作的视图中,有一个小表单供用户创建帖子,并将该帖子提交到显示的聊天室。
但是,当我运行测试时,我收到错误消息“没有路由匹配 [POST] /messages/an_id_of_some_sort”。具体来说,在这个小测试中:
post message_path, params: {message: {body: "yo ho ho and a bottle of rum!"}}
assert_redirected_to chat_room_path(@channel)
post message_path中弹出错误。
聊天室控制器上的show 方法看起来像
def show
if(@user = current_user)
@chats = @user.chat_rooms
@chosen = ChatRoom.find_by(id: params[:id])
if(@chosen.messages.any?)
@messages = @chosen.messages
else
@messages = nil
end
@message = Message.new
end
end
那么视图的小表单位是:
<div class="message-input">
<%= form_for(@message) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.text_area :body, placeholder: "Write Message..." %>
<%= f.hidden_field :room, :value => params[:room] %>
<%= button_tag(type: "submit", class: "message-submit-btn", name: "commit", value: "") do %>
<span class="glyphicon glyphicon-menu-right"></span>
<% end %>
<% end %>
</div>
我在消息控制器上有一个create 操作,用于保存到数据库:
@message = current_user.messages.build(message_params);
@message.chat_room = params[:room]
if @message.save
redirect_to chat_room_path(@message.chat_room)
end
路由方面我有
Rails.application.routes.draw do
root 'welcome#welcome'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get 'users/signup_success'
delete '/chat_rooms/leave/:id', to: 'chat_rooms#leave', as: 'current'
get 'welcome/welcome'
resources :users
resources :account_activations, only: [:edit] #Only providing an Edit route for this resource.
resources :password_resets, only: [:new, :edit, :create, :update]
resources :chat_rooms, only: [:new, :create, :show, :index]
resources :messages, only: [:create, :edit, :destroy]
end
我尝试过在 form_for 上明确设置:url,但没有骰子。关于这个问题还有另一个问题,但那里的解决方案并没有真正帮助。
如果有任何帮助,我将不胜感激。
【问题讨论】:
-
"no route matches [POST] ..."我们可以看看你的routes.rb吗?只有resources :messages, only: [:create, :edit, :destroy]吗? -
aight 对不起,我只把消息放在那里,因为我认为这是唯一相关的部分。我现在将编辑帖子。
-
什么是失败的测试?错误的完整回溯是什么?顺便说一句,您的
ChatRoomsController#show操作包含一个狡猾的if语句——无论如何,您总是会覆盖@message的值。 -
@TomLord 谢谢,我添加了失败的测试部分。另外,
if语句有什么问题?我在这里可能有点昏暗,但我看不出有什么问题。 -
另外,仅供参考,它在 url 中的 ID 是当前聊天室的 ID。
标签: ruby-on-rails ruby forms