Rails 6
bootstrap 4
在我的books_controller.rb中,我有:
def index
@books = Book.select(:id, :name)
end
def new
@book = Book.new
end
def create
@book = Book.new(book_params)
respond_to do |format|
if @book.save
format.html { redirect_to @book, notice: 'Book was successfully created.' }
format.json { render :show, status: :created, location: @book }
else
format.html { render :new }
format.json { render json: @book.errors, status: :unprocessable_entity }
end
end
end
我有一张桌子,在我的views / books / index.htmlslim中,我有:
table.table.table-striped
thead
tr
th Name
tbody
- @books.each do |book|
tr
td = book.name
我想做的是,在表的末尾添加一个表格,允许用户添加书,而无需使用单独的表格,例如:
我尝试过:
= form_with url: new_book_path do |f|
.form-inputs
= f.label 'Add Book'
= f.text_field :book_name
.form-actions
= f.submit
= simple_form_for(@book) do |f|
.form-inputs
= f.input :book_name
但是当我单击submi时,什么也没有发生,并且收到以下消息:
ActionController::RoutingError (No route matches [POST] "/bookd/new"):
另一个想法是将其链接,例如:
= link_to new_book_path, :class => "btn btn-primary btn-lg"
但是我如何传递book_name参数,以及应该执行哪个控制器动作?
这是我的路线:
books GET /books(.:format) books#index
POST /books(.:format) books#create
new_book GET /books/new(.:format) books#new
edit_book GET /books/:id/edit(.:format) books#edit
book GET /books/:id(.:format) books#show
PATCH /books/:id(.:format) books#update
PUT /books/:id(.:format) books#update
DELETE /books/:id(.:format) books#destroy
[在Rails中,您不会通过发布到new
操作来创建资源-您发布到收集路线,例如。 /books
。新操作仅用于创建带有表单的页面。
仍然非常令人困惑,为什么new_book_path
返回/bookd/new
,但错误实际上是正确的。 new_book_path
响应GET-而不是POST。在Rails Routing from the Outside中对此进行了说明。
如果您实际上只是使用:
table.table.table-striped
thead
tr
th Name
tbody
- @books.each do |book|
tr
td = book.name
= simple_form_for(@book || Book.new) do |f|
.form-inputs
= f.input :book_name
它将正确创建带有action="/books" method="POST"
的表格。
我不知道您如何处理这种混乱:
= form_with url: new_book_path do |f|
.form-inputs
= f.label 'Add Book'
= f.text_field :book_name
.form-actions
= f.submit
= simple_form_for(@book) do |f|
.form-inputs
= f.input :book_name
但是the HTML specifications都不允许嵌套<form>
元素,结果可能是不可预测的。例如,提交按钮可以提交内部表单或外部表单。