在数据库中创建对象而不向用户显示视图
我有带有操作 new
的控制器,我希望它创建 ActiveRecord::Base 后代对象,并将其写入数据库(而不向用户显示)。
def new
active_order = current_user.orders.find {|o| o.status > 0 }
active_order = Order.new if active_order.nil?
(...)
end
Order.new
创建本地对象,但我的问题是——如何让 Rails 用默认值填充它并写入数据库?
I have controller with action new
, and I want it to create ActiveRecord::Base descendant object, and write it into database (without showing it to user).
def new
active_order = current_user.orders.find {|o| o.status > 0 }
active_order = Order.new if active_order.nil?
(...)
end
Order.new
creates local object, but my question is -- how to make Rails to fill it with default values and write to database?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 save 方法将未保存的 ActiveRecord 对象实例写入数据库:
但是,它不会自动填充列。如果你想用默认值填充它,你可以在调用 save 之前执行此操作:
或者你可以在调用 new 时传递它:
如果你想做一些更奇特的事情,你可以让 Rails 在保存时自动填充字段,方法是添加类似的内容这对模型来说:
You can write an unsaved ActiveRecord object instance to the database with the save method:
It won't fill in the columns automatically, however. If you want to populate it with default values you can do this before calling save:
Or you can pass it in when you call new:
If you want to do something fancier, you can have Rails automatically populate fields when you save by adding something like this to the model:
您可以使用
Order.Create(...)
它将创建一个新对象并将其保存在数据库中(当然假设 Order 是 ActiveBase 的子级)you can use
Order.Create(...)
which will create a new object and persist it in the database (assuming Order is a child of ActiveBase of course)