RAILS:如何在回调中创建新的collection.build? [英] RAILS: How to make new collection.build in a callback?

查看:134
本文介绍了RAILS:如何在回调中创建新的collection.build?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我试过这行结果是undefined method`journals'for nil:NilClass >

例如

 资源: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
如果user.journals.empty? ?
user.journals.build()????
end
end
end

class Journals< ActiveRecord :: Base
belongs_to:user
end


解决方案<

 

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)


How to create a new record in after_save using other model?

I tried this line which resulted "undefined method `journals' for 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

解决方案

Nested models are going to be saved as well once parent saves, so it's easy to use before_create block and build a nested resource here.

class Profile < ActiveRecord::Base
  belongs_to :user

  before_create do 
    user.journals.build unless user.journals.any?
  end
end

This line of code will create a profile and a journal assigned with the User

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

这篇关于RAILS:如何在回调中创建新的collection.build?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆