我已经使用RESTful技术生成模型(事实上,我正在使用Devise gem,它为我做了这个),并且我在模型中添加了名为first_name和last_name的新字段.迁移进展顺利.我将attr_accessor:first_name,:last_name添加到模型中,并期望它能正常工作.但是当我尝试使用Doctor.create({:first_name =>"MyName"})等大量分配新实例时,我收到错误,说我无法批量分配受保护的属性.
我认为使用attr_accessor的重点是绕过模型字段的保护.你能帮我理解这个消息吗?
编辑:哦,顺便说一下,记录也没有创建.我认为它们应该是因为这只是一个警告,但它们不在数据库中.
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
Run Code Online (Sandbox Code Playgroud)
和模式,它没有first_name和last_name,因为它们是在users表中创建的,这是医生的祖先.我使用单表继承.
create_table :doctors do |t|
t.integer :invitations
t.timestamps
end
Run Code Online (Sandbox Code Playgroud)
这是用于更改users表的迁移
add_column :users, :first_name, :string
add_column :users, :last_name, :string
add_column :users, :type, :string
Run Code Online (Sandbox Code Playgroud)
编辑:这是种子文件.我不包括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")
Run Code Online (Sandbox Code Playgroud) 更新代码格式以便更好地查看.
伙计们,
我一直在看这个,但我不明白这里有什么可能搞乱的.我正在使用Devise.
class User < ActiveRecord::Base
has_many :addresses
accepts_nested_attributes_for :addresses
# Other stuff here
end
class Address < ActiveRecord::Base
belongs_to :user
validates_presence_of :zip #:street_address1,
Run Code Online (Sandbox Code Playgroud)
结束
--------------------日志输出开始--------------------------- ---
在2011-05-28 11:43:27 -0700开始POST"/ users"for 127.0.0.1由RegistrationsController处理#create as HTML参数:{"utf8"=>"√","authenticity_token"=>"CEmdqlsmdYa6Jq0iIf5KAxxISsUCREIrFNXWkP80nhk = ",""user"=> {"email"=>"a2 @ gmail.com","password"=>"[FILT ERED]","addresses_attributes"=> {"0"=> {"street_address1"=> "234 Pitkin Ct.","zip"=>"12456"}}},"commit"=>"注册"}警告:无法批量分配受保护的属性:addresses_attributes SQL(0.0ms)BEGIN SQL(164.0) ms)SHOW TABLES
用户加载(0.0ms)SELECTusers.idFROMusersWHERE(users.--------------------日志输出结束--------------------------- ---
zip已存在于发布的数据中,并且发布的数据似乎已正确格式化.在网页表单上,我收到"地址zip不能为空"的错误.我已经挖了一下导致"无法大量分配受保护属性"的警告,但没有找到任何可以帮助我的东西.
感谢您的想法和指示.
-S
我正在尝试按照Rails指南为帖子创建标签:
tag.rb:
class Tag < ActiveRecord::Base
attr_accessible :name
belongs_to :post
end
Run Code Online (Sandbox Code Playgroud)
post.rb:
class Post < ActiveRecord::Base
attr_accessible :title, :content, :tags
validates :title, :presence => true,
:length => { :maximum => 30 },
:uniqueness => true
validates :content, :presence => true,
:uniqueness => true
belongs_to :user
has_many :comments, :dependent => :destroy
has_many :votes, :as => :votable, :dependent => :destroy
has_many :tags
accepts_nested_attributes_for :tags, :allow_destroy => :true,
:reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }
end …Run Code Online (Sandbox Code Playgroud)