Forum: Ruby on Rails How to create an object in one model at the same time as another

Be2b7277cff8516117cbd7a33df7b03a?d=identicon&s=25 Dave Castellano (dcastellano1)
on 2013-03-10 15:14
Hi,
I'm using Devise and Cancan in my project.  I'm a beginner still.  I'm
trying to create a new Profile object  each time a new user is created.
Anyone know where to do this, as  there is no new action in User
controller.

I have a user model and a Profile model

User model:
user has_one :profile

Profile model:
profile belongs_to :user
5aecb4f86cca29ff0419d764ff37281c?d=identicon&s=25 Jodi S. (jodi_s)
on 2013-03-10 17:17
(Received via mailing list)
use a model callback -
http://api.rubyonrails.org/classes/ActiveRecord/Ca...

:after_create :create_profile

private
  def create_profile
    ...
  end
5f94b9b346c2aa648a80bc259978e5bc?d=identicon&s=25 Colin Law (Guest)
on 2013-03-10 18:02
(Received via mailing list)
On 10 March 2013 14:14, Dave Castellano <lists@ruby-forum.com> wrote:
>
> Profile model:
> profile belongs_to :user
>
> How to create an object in one model at the same time as another

Have a look at the Rails Guide on ActiveRecord Associations and you
will see that for a has_one association there will be a
create_association method defined for you.  So in the create action
for a user, after it is successfully saved you can call create_profile
to create and save a new profile.  Alternatively, as Jodi has
suggested, you could put this in an after_create callback.

Colin
Be2b7277cff8516117cbd7a33df7b03a?d=identicon&s=25 Dave Castellano (dcastellano1)
on 2013-03-10 22:38
after it is successfully saved you can call create_profile
> to create and save a new profile.  Alternatively, as Jodi has
> suggested, you could put this in an after_create callback.
>
> Colin

Thanks.  The after_create callback works nicely as I have no new or
create actions in the users controller using Devise/Cancan.  Not sure
where they but thats another weekend project!
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.