模型创建取决于其他模型创建

时间:2012-11-23 15:17:29

标签: ruby-on-rails ruby-on-rails-3 activerecord model

我有一个Item模型:

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创建一本书。

怎么可能?

2 个答案:

答案 0 :(得分:1)

您需要使用: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

答案 1 :(得分:1)

使用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
相关问题