User is a nested attribute of Announcement. When a new announcement is created, it will create a new user if its email is not found. Otherwise it should just post announcement into the existing user‘s record.
I am not sure which callback to use before_create or before_save. The following code still does not allow new announcement to be posted into the existing user record. A complete newbie, please help.
class Announcement < ActiveRecord::Base
attr_accessible :content, :users_attributes
has_many :users, :through => :awards
accepts_nested_attributes_for :users, :reject_if => lambda { |a| a[:email].blank? }, :allow_destroy => true
before_save :find_user
private
def find_user(user)
If User.find(params[:email]).nil?
@user = User.new
@user.save
else
@user = User.find(params[:email])
end
end
You do not need to use any callbacks at all. Rails handles creating and deleting of nested attributes automatically which makes the accepts_nested_attributes_for macro so great. You should not have to manually save, create, or delete except in your controller when you call new and update_attributes. You may be having problems because your awards association should be defined before your users association. In your code sample I don’t see any definition for an awards association even though your users association is through awards. Otherwise I would check your controller and view code. A common problem I have is passing the wrong parameters from the view (make sure you use the fields_for helper in the view).
http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html