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")

推荐答案

不要把attr_accessorattr_accessible混为一谈.Accessor内置于Ruby中,定义了getter方法model_instance.foo # returns something和setter方法model_instance.foo = 'bar'.

Accessible由Rails定义,并使属性mass可赋值(与attr_protected相反).

如果first_name是模型数据库表中的一个字段,那么Rails已经为该属性定义了getter和setter.你只需要加attr_accessible :first_name.

Ruby-on-rails相关问答推荐

Puma 工作人员无法在 Ubuntu 20.04 VM 上的 Rails 5.2 中启动

组织和/或存储我一直在 RSpec 中使用的模拟对象的最佳方式是什么?

刺激不添加侦听器以搜索表单输入

如何在生成的 HTML 本身中显示部分名称

Rails 7.0.4 和 link_to 的数据确认不起作用

Rspec期望()与期望{}

错误 NoMethodError:ActionView::Base:Class 的未定义方法 `debug_rjs='

Rails:序列化数据库中的对象?

使用带有 bootstrap-sass gem 的 Rails 4 无法让 CSS 在 Heroku 上工作

骨干model.destroy()即使工作正常也会调用错误回调函数?

Gem 更新:在从 ASCII-8BIT 到 UTF-8 到 US-ASCII 的转换中,无法将 "\xE7" 转换为 UTF-8

如何在where子句中组合两个条件?

如何在 routes.rb 中使用 301 或 302 进行重定向

Rails - 从日期和时间戳获取日期

我如何找出为什么我不能#destroy() 记录?

使用 AJAX 向 Rails 发送 Authenticity Token 的正确方法

反编译开发assets资源 管道

Ruby:如何将一种方法接收到的所有参数和块传递给另一种方法?

向 Rails 模型添加外键

将数组传递到 hidden_​​field ROR