I have used RESTful techniques to generate a model (in fact, I am using Devise gem, which does that for me), and I have added new fields called first_name and last_name to the model. Migration went fine. I added attr_accessor :first_name, :last_name to the model and expected it would just work. But when I try to mass-assign new instances with Doctor.create({:first_name=>"MyName"}) etc., I am getting errors saying I can't mass-assign protected attributes.
我认为使用attr_访问器的全部目的是绕过模型字段的保护性.你能帮我理解这个信息吗?
编辑:哦,顺便说一下,这些记录也不会被创建.我想应该是的,因为这只是一个警告,但它们不在数据库中.
Edit2:这是我的模型
class Doctor < User
has_many :patients
has_many :prescriptions, :through=> :patients
validates_presence_of :invitations, :on => :create, :message => "can't be blank"
attr_accessor :invitations
end
模式没有名字和姓氏,因为它们是在doctor 的祖先users表中创建的.我使用单表继承.
create_table :doctors do |t|
t.integer :invitations
t.timestamps
end
这是更改用户表的迁移
add_column :users, :first_name, :string
add_column :users, :last_name, :string
add_column :users, :type, :string
编辑:这是种子文件.我没有包括truncate_db_table方法,但它是有效的.
%w{doctors patients}.each do |m|
truncate_db_table(m)
end
Doctor.create(:invitations=>5, :email=>"email@gmail.com", :first_name=>"Name", :last_name=>"LastName")
Patient.create(:doctor_id=>1, :gender=>"male", :date_of_birth=>"1991-02-24")