RAILS:如何在回调中创建新的collection.build?

如何使用其他模型在after_save中创建新记录?

我试过这一行导致“未定义的方法`期刊’为nil:NilClass”

例如

resources :users do resource :profile resources :journals end class User < ActiveRecord::Base has_one :profile has_many :journals end class Profile < ActiveRecord::Base belongs_to :user after_save :create_new_journal_if_none private def create_new_journal_if_none if user.journals.empty? ???? user.journals.build() ???? end end end class Journals < ActiveRecord::Base belong_to :user end 

父节省后,嵌套模型也将被保存,因此在此处使用before_create块并构建嵌套资源很容易。

 class Profile < ActiveRecord::Base belongs_to :user before_create do user.journals.build unless user.journals.any? end end 

这行代码将创建一个配置文件和一个分配给用户的日志

 User.find(1).create_profile(name :test)