我想将一个值传递给与任何字段无关的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
的值。最好的方法是什么?
将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