我想将值传递给与任何字段都不相关的Mongoid模型,不应该存储在数据库中,而应该用于其他一些操作(例如执行自定义初始化):
class Author
include Mongoid::Document
embeds_many :books
field :name, type: String
# Create a set number of empty books associated with this author.
def create_this_many_books(quantity)
quantity.each do |i|
books << Book.new
end
end
end
class Book
include Mongoid::Document
embedded_in :author
field :title, type: String
end
现在,如何在创建新作者时创建给定数量的嵌入式空book
对象:
author = Author.new(name: 'Jack London', number_of_books: 41)
此处,:number_of_books
不是Author
模型中的字段,而是传递给create_this_many_books
的值。这样做的最佳方式是什么?
答案 0 :(得分:2)
将Author
模型改为
class Author
include Mongoid::Document
embeds_many :books
field :name, type: String
attr_accessor :number_of_books
# this is plain old ruby class member not saved to the db but can be set and get
after_create :create_this_many_books
def create_this_many_books
self.number_of_books.each do |i|
books << Book.new
end
end
end