所以我有一个Message模型和一个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

我试过在表单上显式设置:url,但是没有骰子。关于这个问题还有另一个问题,但解决办法并没有真正起到作用。
我非常感谢你的帮助。

最佳答案

在这一行中,您运行post/messages/:id

post message_path, params: {message: {body: "yo ho ho and a bottle of rum!"}}

在您的路由文件中有:
resources :messages, only: [:create, :edit, :destroy]

这将创建路由post/messages、put/patch/messages/:id和delete/messages/:id。您可以使用rake routes来验证这一点。
这些生成的路由都不处理post/messages/:id。
如果您试图让测试创建新消息,则可以使用messages_pathmessage_path(使用单数message)将消息参数作为消息,例如message_path(Message.first)并使用它来构建url。

09-11 01:27
查看更多