模型创建依赖于其他模型创建



>我有一个项目模型:

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

还有一个书的模型:

class Book < ActiveRecord::Base
  attr_accessible :item_id, :plot
  belongs_to_ :item
end

我希望能够使用

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

它将创建一个带有标题和作者的项目,并使用创建的项目 ID 创建一本书。

怎么可能?

您需要

使用:after_create回调并按如下方式virtual_attributes。

在你的书模型写这个

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

使用 before_save 或 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