Rails Create 方法导致 Nil 记录 [英] Rails Create method resulting in Nil records
问题描述
为什么这个 create 方法会创建一个 nil
记录?
Why does this create method make a nil
record?
我试过了:
Dropdown.create(主题:测试")
Dropdown.create(subject: "test")
Dropdown.create({subject: "test", subject_value: "1"})
Dropdown.create({subject: "test", subject_value: "1"})
Dropdown.create({:subject => "test", :subject_value => "1"})
Dropdown.create({:subject => "test", :subject_value => "1"})
所有结果为 nil
记录.
(0.1ms) begin transaction
SQL (0.6ms) INSERT INTO "dropdowns" ("created_at", "updated_at") VALUES (?, ?) [["created_at", "2016-01-21 23:58:04.979225"], ["updated_at", "2016-01-21 23:58:04.979225"]]
(2.1ms) commit transaction
=> #<Dropdown id: 145, subject: nil, visible: nil, subject_value: nil, subject_description: nil, created_at: "2016-01-21 23:58:04", updated_at: "2016-01-21 23:58:04
模型文件
class Dropdown < ActiveRecord::Base
FIELDS = [
:subject,
:visible,
:subject_value,
:subject_description
]
attr_accessor(*FIELDS)
subjects = %w[math english spanish]
subjects.each do |s|
scope s.to_sym, -> { where(subject: s) }
end
end
迁移文件
class CreateDropdowns < ActiveRecord::Migration
def change
create_table :dropdowns do |t|
t.string :subject
t.boolean :visible
t.string :subject_value
t.string :subject_description
t.timestamps null: false
end
end
end
推荐答案
您通过声明 attr_accessor
:
#app/models/dropdown.rb
class Dropdown < ActiveRecord::Base
subjects = %w(math english spanish)
subjects.each do |s|
scope s.to_sym, -> { where(subject: s) }
end
end
您不需要声明 FIELDS -- 您可以调用
@model.attributes
(instance) 或Model.column_names
(class) 以获取该模型的所有字段.
You don't need to declare FIELDS -- you can call
@model.attributes
(instance) orModel.column_names
(class) to get all the fields for that model.
attr_accessor
创建一组 getter<类中的/code>/
.这会覆盖您可能从数据库中拥有的任何属性,这就是为什么您在保存时获得 setter
方法nil
条目的原因.这里有很好的参考.
attr_accessor
creates a set of getter
/setter
methods in the class. This overrides any attributes you may have from your db, which is why you're getting nil
entries when you save. Good ref here.
--
上述模型应该适合您.
这篇关于Rails Create 方法导致 Nil 记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!