Danpe
Danpe

Reputation: 19047

Model creation depends on other model creation

I have an Item model:

class Item < ActiveRecord::Base
  attr_accessible :author, :title
end

And a Book model:

class Book < ActiveRecord::Base
  attr_accessible :item_id, :plot

  belongs_to_ :item
end

I want to be able to create a book by using

Book.new(:title=>"Title", :author=>"Author", :plot=>"BlaBla")
Book.save

And it will create an Item with the title and author, and also create a Book with the created Item ID.

How is it possible?

Upvotes: 0

Views: 138

Answers (2)

Super Engineer
Super Engineer

Reputation: 1976

You need to use :after_create callback and virtual_attributes as follows.

In you book model write this

attr_accessor :title, :author

attribute_accessible :title, :author, :plot

after_create :create_item

def create_item
  item = self.build_item(:title => self.title, :author => self.author)
  item.save
end

Upvotes: 1

Santosh
Santosh

Reputation: 1261

Using before_save or before_create

class Book
  attr_accessor :title, :author

  before_save :create_item

  #before_create :create_item

  def create_item
    if self.title.present? && self.autor.present?
      item = Item.new(:title => self.title, :author => self.author)
      item.save(:validate => false)
      self.item = item # or self.item_id = item.id
    end
  end
end

Upvotes: 1

Related Questions