Automatically creating associated records with after_create

Hi all.

I am actually using ActiveRecord outside of Rails but I don’t see that
it matters for this question.

I want to automatically create a registration entry when I add a new
user to my application. This works fine, but it’s not automatic:

class User < ActiveRecord :: Base
has_many :registrations
end

class Test
user = User.new
user.registrations.create
end

I’d like the User class to do that automatically. I tried this but it
didn’t work:

class User < ActiveRecord :: Base
has_many :registrations
after_create {
self.registrations.create
}
end

I feel like I’m just missing some syntax. Can anyone help?

Thanks!

/adam

Adam B. <[email protected]…> writes:

class User < ActiveRecord :: Base
has_many :registrations
after_create {
self.registrations.create
}
end

self.registrations returns a list of Registration objects, and that list
(I
assume it’s just an array) doesn’t have a .create method

self.registrations << Registration.new # should work though

The above should be read as “Append a new registration to
self.registrations”

Gareth

Thanks for the reply.

But I’m confused: if that’s the case, how come user.registrations.create
works?

Anyway, I tried adding this line to the User class:

after_create { self.registrations << Registration.new(({:timestamp =>
Time.now})) }

And I got this error:

…/gems/activerecord-1.14.4/lib/active_record/base.rb:1129:in
method_missing': undefined methodregistrations’ for User:Class
(NoMethodError)

Also, my Registration class looks like:

class Registration < ActiveRecord::Base
belongs_to :users
end

I appreciate the assistance!

/afb

Adam B. wrote:

Also, my Registration class looks like:

class Registration < ActiveRecord::Base
belongs_to :users
end

You might try using ‘belongs_to :user’. The ActiveRecord parser is
exacting in the names used in one-to-many models.

Jose

Jose, you are right and I fixed that but was still having the same
problem.

Then I changed my User class to:

class User < ActiveRecord :: Base
has_many :registrations
after_create :create_new_registration

private
def create_new_registration
self.registrations << Registration.new
end
end

And that worked. Thanks all for your suggestions.

/afb

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs