【问题标题】:Model creation depends on other model creation模型创建依赖于其他模型创建
【发布时间】:2012-11-23 15:17:29
【问题描述】:

我有一个项目模型:

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

这怎么可能?

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

    • 但是这里 book.item_id 将是 nil,因为 book 是先保存的,当时 item_id 是 nil(项目不存在)。
    • 你试过这样做吗?它不应该发生,因为当您通过 book 对象创建项目时,id 会自动保存。如果它不起作用,请告诉我。
    • @SuperEngineer 为什么不使用 before_create 然后设置 item_id?
    • @SuperEngineer Yes before_create 或 before_save 将正常工作。
    • 我已经编辑了答案。上一个有一些错误。您也可以使用 before_create。你应该首先创建项目并在 before_create 回调中设置 book 的 item_id。
    【解决方案2】:

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

    【讨论】:

    • 实际上我在设置项目属性时得到了 ActiveModel::MassAssignmentSecurity。
    猜你喜欢
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2015-02-18
    • 1970-01-01
    相关资源
    最近更新 更多