Frage

I want to pass a value to a Mongoid model that is not correlated with any field and should not be stored in the database, but should instead be used for some additional actions (e.g. performing custom initialization):

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

Now, how can I create a given number of embedded empty book objects when creating a new author:

author = Author.new(name: 'Jack London', number_of_books: 41)

Here, :number_of_books is not a field in the Author model, but a value passed to create_this_many_books. What is the best way of doing this?

War es hilfreich?

Lösung

alter the Author model to be

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top