Rails 4 不将值插入数据库 [英] Rails 4 not inserting values into database

查看:37
本文介绍了Rails 4 不将值插入数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个小型演示应用程序,以帮助自己了解如何在 Rails 4 上实现级联选择,但我遇到了一个有趣的问题:

当我填写表单并将其提交到数据库时,参数似乎已传递,但值并未保存在数据库中,因为 SQL 跳过了字段名称和值,如以下代码段所示控制台:

在 2015-01-23 18:54:05 -0800 开始为 ::1 POST "/prop_sub_types"由 PropSubTypesController#create 处理为 HTML参数:{"utf8"=>"✓", "authenticity_token"=>"7mGqF/MR+IKrKKdAKBYBI/E7pl7PCJasHDLN5T1/ohF/qEuXyhwsm8d87xDvfmcxk590hp/2Xuenname">"subpda=">GqF/MR+IKrKKdAKBYBI/E7pl7PCJasHDLN5T1/ohm>"sub foo", "prop_type_id"=>"1"}, "commit"=>"创建 Prop 子类型"}(0.1ms) 开始事务SQL (0.3ms) INSERT INTO "prop_sub_types" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2015-01-24 02:54:05.218673"], ["updated_at","2015-01-24 02:54:05.218673"]](2.2ms) 提交事务重定向到 http://localhost:3000/prop_sub_types/17ms 内完成 302 Found (ActiveRecord: 2.6ms)

这是 schema.rb 的相关部分,用于证明列在那里:

 create_table "prop_sub_types", force: :cascade do |t|t.string "名称"t.integer "prop_type_id"t.datetime "created_at", null: falset.datetime "updated_at", null: false结尾

型号:

class PropSubType 

控制器(为了简洁起见,我可以发布更多相关部分):

def 创建@prop_sub_type = PropSubType.new(prop_sub_type_params)response_to do |格式|如果@prop_sub_type.saveformat.html { redirect_to @prop_sub_type,注意:'Prop 子类型已成功创建.'}format.json { 渲染:显示,状态::创建,位置:@prop_sub_type }别的format.html { 渲染:新}format.json { 渲染 json:@prop_sub_type.errors,状态::unprocessable_entity }结尾结尾结尾

...

私有# 使用回调在动作之间共享公共设置或约束.def set_prop_sub_type@prop_sub_type = PropSubType.find(params[:id])结尾# 永远不要相信来自可怕互联网的参数,只允许白名单通过.def prop_sub_type_paramsparams.require(:prop_sub_type).permit(:name, :prop_type_id)结尾

app/views/prop_sub_types/_form.html.erb:

<%= form_for(@prop_sub_type) do |f|%><% if @prop_sub_type.errors.any?%><div id="error_explanation"><h2><%=pluralize(@prop_sub_type.errors.count, "error") %>禁止保存这个 prop_sub_type:</h2><ul><% @prop_sub_type.errors.full_messages.each do |message|%><li><%=消息%></li><%结束%>

<%结束%><div class="field"><%= f.label :name %><br><%= f.text_field :name %>

<div class="field"><%= f.label :prop_type_id %><br><%= f.number_field :prop_type_id %>

<div class="actions"><%= f.submit %>

<%结束%>

我正在改编一些 Rails 3 代码,所以我认为我搞砸了强参数部分,但代码实际上对我来说是正确的,并且与一个无关但可以工作的 Rails 4 应用程序进行了比较.

我做错了什么让 INSERT 忽略我的参数?

解决方案

我相信这是因为你的 attr_accessor :name, :prop_type_id 在模型中.这些访问器肯定是多余的并且会覆盖正确的访问器:数据库表字段的所有字段都是作为初始化 AR:Base 类的一部分创建的

I'm working on a small demo app to help myself understand how to implement cascading selects on Rails 4, but I've run into an interesting problem:

When I fill out a form and submit it to the database, the parameters seem to be passed, but the values are not being saved in the database because the SQL skips the field names and values, as demonstrated in this snippet from the console:

Started POST "/prop_sub_types" for ::1 at 2015-01-23 18:54:05 -0800
Processing by PropSubTypesController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"7mGqF/MR+IKrKKdAKBYBI/E7pl7PCJasHDLN5T1/ohF/qEuXyhwsm8d87xDvfmcxk590hp/2XuenQBDaGhI+IA==", "prop_sub_type"=>{"name"=>"sub foo", "prop_type_id"=>"1"}, "commit"=>"Create Prop sub type"}
   (0.1ms)  begin transaction
  SQL (0.3ms)  INSERT INTO "prop_sub_types" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", "2015-01-24 02:54:05.218673"], ["updated_at", "2015-01-24 02:54:05.218673"]]
   (2.2ms)  commit transaction
Redirected to http://localhost:3000/prop_sub_types/1
Completed 302 Found in 7ms (ActiveRecord: 2.6ms)

This is the relevant bit of schema.rb that demonstrates that the columns are there:

  create_table "prop_sub_types", force: :cascade do |t|
    t.string   "name"
    t.integer  "prop_type_id"
    t.datetime "created_at",   null: false
    t.datetime "updated_at",   null: false
  end

Model:

class PropSubType < ActiveRecord::Base
  attr_accessor :name, :prop_type_id

  belongs_to :prop_type
  has_many :appraisals
end

Controller (relevant portions for the sake of brevity -- I can post more if needed):

def create
    @prop_sub_type = PropSubType.new(prop_sub_type_params)

    respond_to do |format|
      if @prop_sub_type.save
        format.html { redirect_to @prop_sub_type, notice: 'Prop sub type was successfully created.' }
        format.json { render :show, status: :created, location: @prop_sub_type }
      else
        format.html { render :new }
        format.json { render json: @prop_sub_type.errors, status: :unprocessable_entity }
      end
    end
  end

...

private
    # Use callbacks to share common setup or constraints between actions.
    def set_prop_sub_type
      @prop_sub_type = PropSubType.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def prop_sub_type_params
      params.require(:prop_sub_type).permit(:name, :prop_type_id)
    end

app/views/prop_sub_types/_form.html.erb:

<%= form_for(@prop_sub_type) do |f| %>
  <% if @prop_sub_type.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@prop_sub_type.errors.count, "error") %> prohibited this prop_sub_type from being saved:</h2>

      <ul>
      <% @prop_sub_type.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :prop_type_id %><br>
    <%= f.number_field :prop_type_id %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

I'm adapting some Rails 3 code, so I thought I messed up the strong parameters portion, but the code actually looks correct to me and compares well with an unrelated, but working Rails 4 application.

What did I do wrong to make the INSERT ignore my parameters?

解决方案

I believe it is because of your attr_accessor :name, :prop_type_id in model. Those accessors definitely are redundant and override the right ones: all fields for the DB table's fields are created as a part of initializing AR:Base class

这篇关于Rails 4 不将值插入数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆