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

时间:2012-07-08 05:57:09

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

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

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

e.g。

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

1 个答案:

答案 0 :(得分:1)

嵌套模型也将在父节省后保存,因此很容易使用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)