如何从模型 B 的视图内的窗体创建模型 A 的实例



所以我有一个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

我尝试在form_for上显式设置: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)并使用它来构建网址。

最新更新