Adam Block
2006-Aug-17 06:13 UTC
[Rails] 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 -- Posted via http://www.ruby-forum.com/.
Gareth Adams
2006-Aug-17 07:41 UTC
[Rails] Re: Automatically creating associated records with after_create
Adam Block <adam@...> writes:> class User < ActiveRecord :: Base > has_many :registrations > after_create { > self.registrations.create > } > endself.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
Adam Block
2006-Aug-17 22:54 UTC
[Rails] Re: Automatically creating associated records with after_cre
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 method `registrations'' for User:Class (NoMethodError) Also, my Registration class looks like: class Registration < ActiveRecord::Base belongs_to :users end I appreciate the assistance! /afb -- Posted via http://www.ruby-forum.com/.
Jose Hales-Garcia
2006-Aug-18 05:15 UTC
[Rails] Re: Automatically creating associated records with after_cre
Adam Block wrote:> Also, my Registration class looks like: > > class Registration < ActiveRecord::Base > belongs_to :users > endYou might try using ''belongs_to :user''. The ActiveRecord parser is exacting in the names used in one-to-many models. Jose -- Posted via http://www.ruby-forum.com/.
Adam Block
2006-Aug-18 06:13 UTC
[Rails] Re: Automatically creating associated records with after_cre
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 -- Posted via http://www.ruby-forum.com/.