我創建了一個編輯頁面來編輯房間(模型)并更新表單以將當前名稱和當前容量更改為我們想要的任何內容但是我收到錯誤
ActionController::ParameterMissing in RoomsController#edit
param is missing or the value is empty: room
房間控制器.rb
class RoomsController < ApplicationController
before_action :set_room, only: %i[show edit update]
def index
@rooms = Room.all
end
def show
end
def new
@room = Room.new
end
def create
@room = Room.new(room_params)
respond_to do |format|
if @room.save
format.html { redirect_to room_url(@room), notice: "Room was created Successfully" }
else
format.html { render :new, status: :unprocessable_entity }
end
end
end
def edit
respond_to do |format|
if @room.update(room_params)
format.html { redirect_to room_url(@room), notice: "Room was successfully updated!" }
else
format.html { render :edit, status: :unprocessable_entity }
end
end
end
private
def set_room
@room = Room.find(params[:id])
end
def room_params
params.require(:room).permit(:name, :capacity)
end
end
編輯.hml.erb
<h2>Edit Room</h2>
<%= render "form", room: @room %>
_form.html.erb
<%= form_with(model: room) do |form| %>
<% if room.errors.any? %>
<div style="color: red">
<h2><%= pluralize(room.errors.count, "errors") %> Prohibited this Room from saving</h2>
<ul>
<% room.errors.each do |error| %>
<li><%= error.full_message %></li>
<% end %>
</ul>
</div>
<% end %>
<div>
<%= form.label :name, style: "display: block" %>
<%= form.text_field :name %>
</div>
<div>
<%= form.label :capacity, style: "display: block" %>
<%= form.number_field :capacity %>
</div>
<div>
<%= form.submit %>
</div>
<% end %>
我_form.html.erb對new.html.erb和都使用相同的edit.html.erb部分,是因為使用相同的部分形式進行編輯和新建還是有其他原因?
新的.html.erb
<h1>New Room</h1>
<%= render "form", room: @room %>
uj5u.com熱心網友回復:
您正在使用錯誤的操作。
在Rails 風格的 REST中,edit操作回應GET /rooms/:id/edit請求并僅呈現表單。它也應該是冪等的。沒有room引數,因為您沒有回應表單提交。
更新資源是在update方法 ( PATCH /rooms/:id) 中完成的。
class RoomsController < ApplicationController
# ...
# you can actually completely omit this method
# Rails will implicitly render edit.html.erb anyways
# GET /rooms/1/edit
def edit
end
# PATCH /rooms/1
def update
# you don't need to use MimeResponds if you're only responding to HTML requests. KISS
if @room.update(room_params)
redirect_to @room, notice: "Room was successfully updated!"
else
render :edit, status: :unprocessable_entity
end
end
# ...
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/536869.html
