"Simple Form" 数据未插入数据库

"Simple Form" data not inserting into database

我有一个看起来像这样的表格

<%= simple_form_for @contact_form, url: contact_form_index_path, method: :post do |f| %>
    <%= f.input :first_name, placeholder: 'Jane' %>
    <%= f.input :last_name, placeholder: 'Doe' %>
    <%= f.input :email, placeholder: 'example@email.com' %>
    <%= f.input :address, placeholder: '123 Main Street' %>
    <%= f.input :city, placeholder: 'Pleasantville' %>
    <%= f.input :state, placeholder: 'NJ' %>
    <%= f.input :zip_code, placeholder: '12345' %>
    <%= f.input :phone, placeholder: '(123) 456-7890' %>
    <%= f.button :submit %>
<% end %>

我的数据库架构如下所示;

create_table "contact_forms", force: :cascade do |t|
    t.string   "first_name"
    t.string   "last_name"
    t.string   "email"
    t.string   "address"
    t.string   "city"
    t.string   "zip_code"
    t.string   "state"
    t.integer  "phone"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

我的控制器如下所示;

class ContactFormController < ApplicationController
    def new
        @contact_form = ContactForm.new
    end

    def create
        @contact_form = ContactForm.new

        if @contact_form.save
            redirect_to pages_url
        else
            render :new
        end
    end
end

当我测试表单并尝试 post 将输入的数据输入我的数据库时,我没有收到错误,但数据没有填充到 table.

您知道是什么原因造成的吗?以下是日志,如果有帮助的话。

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"IniAUnB4O51+1KrNy5Ip/nVPqmEZaXopoFozaBu98bkvg0MP5GxbEkzKKltY/QuVomxE2hnDT7cIloy99u0Nsw==", "contact_form"=>{"first_name"=>"Jack", "last_name"=>"Burum", "email"=>"", "address"=>"", "city"=>"", "state"=>"", "zip_code"=>"", "phone"=>""}, "commit"=>"Create Contact form"}
   (0.1ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "contact_forms" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2015-11-27 18:37:45.421056"], ["updated_at", "2015-11-27 18:37:45.421056"]]
   (7.3ms)  commit transaction
Redirected to http://localhost:3000/pages
Completed 302 Found in 11ms (ActiveRecord: 7.7ms)

所以我需要添加一个私有方法,我称之为 'contact params'。在这种方法中,我允许访问我在表单中需要的数据。

我仍然不是 100% 清楚为什么当您希望创建方法可以访问所有数据时需要允许数据属性。

现在可以了。

使用批量赋值创建记录时,如果您的控制器不允许参数,Rails 将抛出错误。这是为了阻止人们将您不希望的东西注入您的数据库。

假设您有一个注册表单,您只想接受用户的姓名和电子邮件地址,但还要考虑到您的 table 上有一列名为 is_admin

通常,您的表单会在表单的参数散列中提交 :name:email,但请想象一下,攻击者构建了他们自己的 POST 请求并插入 :is_admin => true 以及其余数据。很明显你希望你的控制器忽略请求的那部分!

因此,在步骤强参数。启用此功能(默认情况下),您必须明确允许您愿意接受的参数散列的元素。在上面的例子中,你会使用这样的东西:

params.require(:user).permit(:name, :email)

这将要求 params 中有一个 :user 元素,并允许 :user 提供 :name:email 但什么也没有更多

但是,当您必须更改允许的参数时,在控制器的很多地方使用它很快就会变得烦人,因此通常将它放在私有方法中并从那里引用它:

private

def user_params
  params.require(:user).permit(:name, :email)
end

然后,您只需在控制器中需要使用它们的任何位置调用 user_params 方法即可!

因此,在您的情况下(正如您已经意识到的那样),您应该创建一个私有方法,该方法应该 return 您愿意接受的允许参数,并在创建模型记录时使用该方法.