我只是学习RoR,现在混淆了如何将数据插入db。这是我的代码:
book_insert.html.erb
<%= content_for :helloworld do %>
<%= form_tag("/insert", method: "post") do %>
<%= label_tag(:title, "Title") %>
<%= text_field_tag(:title) %><br>
<%= label_tag(:price, "Price") %>
<%= number_field_tag(:price) %><br>
<%= label_tag(:subject_id, "Subject ID") %>
<%= number_field_tag(:subject_id) %><br>
<%= label_tag(:description, "Description") %>
<%= text_field_tag(:description) %><br>
<br>
<%= submit_tag("Submit") %>
<% end %>
<% end %>
book_controller.rb
class BookController < ApplicationController
def insert
@book = Book.new(book_params)
@book.save
render :book_page
end
def book_params
params.require(:books).permit(:title, :price, :subject_id, :description)
end
def showinsert
render :book_insert
end
end
它返回错误:
在4毫秒内完成了400错误请求(ActiveRecord:0.0毫秒) ActionController :: ParameterMissing(缺少参数或值为 空:书籍):
请帮助。谢谢
答案 0 :(得分:2)
form_tag
通常用于向映射的controller#action
提交非模型动作。您可能需要在表单内使用form_for
及其相应的助手
<%= content_for :helloworld do %>
<%= form_for Book.new, url: "/insert", method: "post" do |f| %>
<%= f.label :title %>
<%= f.text_field :title %><br>
<%= f.label :price %>
<%= f.number_field :price %><br>
<%= f.label :subject_id %>
<%= f.number_field :subject_id %><br>
<%= f.label :description %>
<%= f.text_field :description %><br>
<br>
<%= f.submit "Submit" %>
<% end %>
<% end %>
使用上面的代码,params
将传递到:book => {}
哈希中,因此您需要将book_params
更改为下面的
def book_params
params.require(:book).permit(:title, :price, :subject_id, :description)
end #^
答案 1 :(得分:2)
params.require
方法要求密钥books
存在于哈希中-如果不存在,则会引发ActionController::ParameterMissing
异常。
要嵌套输入,您需要相应地命名它们:
<%= form_tag("/insert", method: "post") do %>
<%= label_tag("Title") %>
<%= text_field_tag("books[title]") %><br>
<%= label_tag("Price") %>
<%= number_field_tag("books[price]") %
...
<%= submit_tag("Submit") %>
<% end %>
这将使参数散列:
{ books: { title: 'Life & Times of Michael K', price: 99 } }
但是那很乏味。更好的方法是使用表单助手,并按照约定设置路由和控制器:
# config/routes.rb
resources :books
# app/views/books/new.html.erb
<%= form_for(@book) do |f| %>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title %>
</div>
# ...
<%= f.submit %>
<% end %>
# app/controllers/books_controller.rb
class BooksController < ApplicationController
# this renders the form to create a new book
# GET /books/new
def new
@book = Book.new
end
# In Rails its called create - not insert
# POST /books
def create
@book = Book.new(book_params)
if @book.save
redirect_to @book
else
render :new
end
end
# This is the path to show a book
# its also where we redirect after creating the book
# GET /books/:id
def show
@book = Book.find(params[:id])
end
# ...
private
def book_params
# note thats its book singular - not plural
params.require(:book).permit(:title, :price, :subject_id, :description)
end
end
答案 2 :(得分:-1)
您应该在book
方法中执行book_params
,而不是books
:
def book_params
params.require(:book).permit(:title, :price, :subject_id, :description)
end