开发者

Ruby on Rails 3 - create an instance of one model from another model

开发者 https://www.devze.com 2023-03-28 21:40 出处:网络
I have the following problem, but first I will make some assumptions The example is just to explain my problem in an easy way

I have the following problem, but first I will make some assumptions

  1. The example is just to explain my problem in an easy way
  2. The tables models are not related

I have two tables (models) Users an Emails

Users

  • id
  • name
  • email

Emails

  • id
  • account

So, the idea is every time I create a user, I want to create an instance of Email, where Emails.account = Users.email

I tried using callback

def after_create
   Email.create!(:account => user.email)
end

But it d开发者_Python百科idn't work.

Is there another way to achieve this?


You are almost there, except you don't need to reference a 'user' variable in your after_create because you are in the User model.

Try the following:

class User < ActiveRecord::Base 
  after_create :create_email
  def create_email
     Email.create!(:account => email)
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消