Ruby on rails 如何从模型B视图中的表单创建模型A的实例

Ruby on rails 如何从模型B视图中的表单创建模型A的实例,ruby-on-rails,ruby,forms,Ruby On Rails,Ruby,Forms,所以我有一个消息模型和一个聊天室模型 当我显示聊天室时,我使用聊天室控制器上的show操作。在该操作的视图中,有一个小表单供用户创建帖子,并将该帖子提交到显示的聊天室 然而,当我运行测试时,我得到一个错误“没有路由匹配[POST]/messages/an\u id\u some\u sort”。具体来说,在这个小测试中: post message_path, params: {message: {body: "yo ho ho and a bottle of rum!"}} assert_red

所以我有一个
消息
模型和一个
聊天室
模型

当我显示聊天室时,我使用聊天室控制器上的
show
操作。在该操作的视图中,有一个小表单供用户创建帖子,并将该帖子提交到显示的聊天室

然而,当我运行测试时,我得到一个错误“没有路由匹配[POST]/messages/an\u id\u some\u sort”。具体来说,在这个小测试中:

post message_path, params: {message: {body: "yo ho ho and a bottle of rum!"}}
assert_redirected_to chat_room_path(@channel)
错误会在
post message\u路径中弹出

聊天室控制器上的
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>
我有

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\u path
<代码>消息路径
(使用单数
消息
)将消息参数作为消息,例如
消息路径(message.first)
,并使用该参数构建url

“没有路由匹配[POST]…”
我们可以看看您的
路由.rb
?,是否只有
资源:消息,仅:[创建,:编辑,:销毁]
?对不起,我只在那里放了消息位,因为我认为这是唯一相关的部分。我现在就编辑这篇文章。什么考试不及格?错误的完整回溯是什么?顺便说一句,你的
ChatRoomsController#show
操作包含一个狡猾的
if
语句——不管怎样,你总是覆盖
@message
的值。@TomLord谢谢,我添加了测试失败的部分。还有,
if
语句有什么问题?我可能有点糊涂,但我看不出有什么问题。另外,仅供参考,它在url中的ID是当前聊天室的ID。
resources :messages, only: [:create, :edit, :destroy]