如何避免验证、回调和“attr_accessible”使用 Ruby on Rails 3 进行播种过程有何影响?
我正在使用 Ruby on Rails 3,并尝试在我的应用程序数据库中播种数据。
在“RAILS_ROOT/models/user.rb”中,我有:
class User < ActiveRecord::Base
attr_accessible #none
validates :name,
:presence => true
validates :surname,
:presence => true
validates :email,
:presence => true
end
在“RAILS_ROOT/db/seeds.rb”中,我有:
# Test 1
User.find_or_create_by_email (
:name => "Test1 name",
:surname => "Test1 surname",
:email => "[email protected]"
)
# Test2
User.find_or_create_by_email (
:name => "",
:surname => "",
:email => "[email protected]"
)
因此,在终端中运行,
rake db:seed
数据库当然不会填充数据,因为“attr_accessible”为零(案例测试1) )并且验证未通过(案例测试2)。
我想在播种过程中跳过验证和“可访问属性的效果”。 这可能吗?如果是这样,该怎么做?
PS:我不想在“RAILS_ROOT/db/migrate/201....rb”代码中使用这样的代码:
execute "INSERT INTO users ( name, surname, email ) VALUES ( "Test1 name", "Test1 surname", "[email protected]")"
UPDATE
我需要还可以跳过所有回调。 可能吗?如果是这样,怎么办?
I am using Ruby on Rails 3 and I am trying to seed data in my application database.
In 'RAILS_ROOT/models/user.rb' I have:
class User < ActiveRecord::Base
attr_accessible #none
validates :name,
:presence => true
validates :surname,
:presence => true
validates :email,
:presence => true
end
In 'RAILS_ROOT/db/seeds.rb' I have:
# Test 1
User.find_or_create_by_email (
:name => "Test1 name",
:surname => "Test1 surname",
:email => "[email protected]"
)
# Test2
User.find_or_create_by_email (
:name => "",
:surname => "",
:email => "[email protected]"
)
So, running in the Terminal
rake db:seed
of course the database will NOT populate with datas because 'attr_accessible' to nil (Case Test1) and validation not passed (Case Test2).
I would like to skip the validation and "attr-accessible effects" during the seeding process. Is it possible? If so, how to do that?
P.S.: I don't want to use in 'RAILS_ROOT/db/migrate/201....rb' code like this:
execute "INSERT INTO users ( name, surname, email ) VALUES ( "Test1 name", "Test1 surname", "[email protected]")"
UPDATE
I need also to skip all callbacks. Is it possible? If so, how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您检查 ActiveRecord 的文档,您会看到
attributes=
方法有一个参数来启用此功能:attributes=(new_attributes,guard_protected_attributes = true)
像这样使用它:
If you check ActiveRecord's documentation you'll see the
attributes=
method has a parameter to enable this:attributes=(new_attributes, guard_protected_attributes = true)
Use it like this: